用httpPost对JSON发送和接收的例子
2015-12-11 00:00
453 查看
HTTPPost发送JSON:
接收HTTPPost中的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进行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); }
相关文章推荐
- 使用ConcurrentQueue并发集合来设计网络服务器端
- TCP 协议状态解析
- 自己动手写网络爬虫(第一天)
- Android Fiddler 手机抓包 Http 数据
- Android中使用代码控制Wifi及数据连接网络开关
- B树、B-树、B+树、B*树http://www.cnblogs.com/oldhorse/archive/2009/11/16/1604009.html
- 异步block网络请求
- 10G(82599EB) 网卡测试优化(jumbo frame, tcp win scaling)
- 网络基础
- http权威指南-第二章-URL与资源
- ImageLoader(UIL)自定义HTTP Header信息
- 网络地址转换(NAT)
- HTTP server git
- AFNetworking    在MRC下使用AF第三方网络请求数据     加  -fobjc-arc
- 运输层—TCP
- 计算机网络:应用层
- TCP与UDP区别
- 浅析Android系统中HTTPS通信的实现
- 网络流量限制
- Apache服务的HTTPS支持配置