用httpPost对JSON发送和接收的例子
2015-12-09 16:30
501 查看
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进行UTF-8编码,以便传输中文
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 {
// 读取请求内容
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);
}
相关文章推荐
- memcached 网络模型 --转载处:
- 质问微软 WP8.1开发HTTPS 真费劲
- UVA-10779 Collectors Problem (网络流建模)
- UDP和TCP
- 操作系统与网络实现 之十一
- 操作系统与网络实现 之十一
- 网络虚拟化之FlowVisor:网络虚拟层(中)
- 分享一些灵活高效运用OkHttp的技巧和强有力的内省。
- [Servlet&JSP] HttpServletRequest的使用
- VirtualBox 四种网络连接
- NetFlow网络流量监测技术的应用和设计(转载)
- httpClient4.5创建连接池进行post请求
- linux基础(六)----linux命令系统学习----网络操作命令
- linux基础(六)----linux命令系统学习----网络操作命令
- HttpClient的使用(模拟登录)
- TCP与UDP的区别
- 实验三同学评论http://home.cnblogs.com/u/MyDring/
- https与http的区别
- TCP参数调优详解
- JAVA调用https协议