Apache http 发送post请求,解析响应,apachepost
Apache http 发送post请求,解析响应,apachepost
<span > UrlEncodedFormEntity formEntiry = null;
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "hqq1007"));
formParams.add(new BasicNameValuePair("age", "26"));
try {
formEntiry = new UrlEncodedFormEntity(formParams);
} catch (UnsupportedEncodingException e1) {
logger.error("UrlEncodedFormEntity Error!", e1);
}
HttpPost httpPost = new HttpPost("localhost:8080/hqq1007/test");
httpPost.setEntity(formEntiry);
HttpResponse httpResponse = null;
try {
httpResponse = new DefaultHttpClient().execute(httpPost);
} catch (ClientProtocolException e) {
logger.error("ClientProtocolException!", e);
} catch (IOException e) {
logger.error("IOException!", e);
}
/*将返回的响应的消息体转换为字符输入流*/
InputStream is = httpResponse.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
StringBuffer sb = new StringBuffer();
String str = br.readLine();
while (str != null) {
sb.append(str + (char) 13 + (char) 10);
str = br.readLine();
}
/*json字符串格式转换成json对象格式*/
JSONObject responseContext = new JSONObject(sb.toString());
String message = responseContext.getString("result");
String result = responseContext.getString("message");</span>
返回值格式为json
返回的消息体格式为:
{
result:0,
message:this is hqq1007
}
评论暂时关闭