httpPost對JSON發(fā)送和接收
來源:程序員人生 發(fā)布時間:2016-11-22 08:36:22 閱讀次數(shù):9585次
public static String postURL(String commString, String address, String encode) {
String rec_string = "";
URL url = null;
HttpURLConnection urlConn = null;
try {
/*得到url地址的URL類*/
url = new URL(address);
/*取得打開需要發(fā)送的url連接*/
urlConn = (HttpURLConnection) url.openConnection();
/*設(shè)置連接超時時間*/
urlConn.setConnectTimeout(30000);
/*設(shè)置讀取響應(yīng)超時時間*/
urlConn.setReadTimeout(30000);
/*設(shè)置post發(fā)送方式*/
urlConn.setRequestMethod("POST");
/*發(fā)送commString*/
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
OutputStreamWriter out;
out = new OutputStreamWriter(urlConn.getOutputStream(), encode);
out.write(commString);
out.flush();
out.close();
/*發(fā)送終了 獲得返回流,解析流數(shù)據(jù)*/
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), encode));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > ⑴) {
sb.append((char) ch);
}
rec_string = sb.toString().trim();
/*解析終了關(guān)閉輸入流*/
rd.close();
} catch (Exception e) {
/*異常處理*/
rec_string = "⑴07";
System.out.println(e);
} finally {
if (urlConn != null) {
/*關(guān)閉URL連接*/
urlConn.disconnect();
}
}
/*返回響應(yīng)內(nèi)容*/
return rec_string;
}
上面是另外一種方式的要求
下面是httpost:
HTTPPost發(fā)送JSON:
private static final String APPLICATION_JSON = "application/json";
private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
public static void httpPostWithJSON(String url, String json)
throws Exception {
// 將JSON進(jìn)行UTF⑻編碼,以便傳輸中文

String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);

DefaultHttpClient httpClient =
new DefaultHttpClient();

HttpPost httpPost =
new HttpPost(url);

httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);

StringEntity se =
new StringEntity(encoderJson);

se.setContentType(CONTENT_TYPE_TEXT_JSON);

se.setContentEncoding(
new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));

httpPost.setEntity(se);

httpClient.execute(httpPost);

}
接收HTTPPost中的JSON:
public static String receivePost(HttpServletRequest request)
throws IOException, UnsupportedEncodingException {
// 讀取要求內(nèi)容

BufferedReader br =
new BufferedReader(
new InputStreamReader(request.getInputStream()));

String line =
null;

StringBuilder sb =
new StringBuilder();
while((line = br.readLine())!=
null){

sb.append(line);

}
// 將資料解碼

String reqBody = sb.toString();
return URLDecoder.decode(reqBody, HTTP.UTF_8);

}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈