用httpPost对JSON发送和接收的例子
2016-04-06 11:00
651 查看
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);
}
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);
}
相关文章推荐
- TCP之非阻塞connect和accept
- K60 Lwip TCP Server实现
- TCP
- 用Java发起HTTP请求与获取状态码(含状态码列表)
- Linux C实现简单的网络聊天室
- python 获取网络时间及修改本地时间
- 网络工具wireshark和tcpdump以及netstat命令的使用
- 搭建SSL,让Apache支持Https
- HTTP Status 404 - No result defined for action com.csdhsm.struts.action.LoginAction and result error
- 写给后端程序员的HTTP缓存原理介绍
- 深入理解HTTP Session
- GetAPictureFromInternet网络编程
- SVN基于http协议
- 计算机网络知识点(一)
- http://www.blogjava.net/soken/articles/371548.html
- Android OkHttp完全解析
- Linux C高级编程——网络编程之API(5)
- 告别砸钱深挖潜力 动漫、音频、游戏重构IP新玩法
- HttpUtils工具类
- 【bzoj 1070】【codevs 2436】[SCOI2007]修车(费用流)