zoukankan      html  css  js  c++  java
  • 用httpPost对JSON发送和接收

    HTTPPost发送JSON:

     1 private static final String APPLICATION_JSON = "application/json";
     2     
     3     private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
     4 
     5 public static void httpPostWithJSON(String url, String json) throws Exception {
     6         // 将JSON进行UTF-8编码,以便传输中文
     7         String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
     8         
     9         DefaultHttpClient httpClient = new DefaultHttpClient();
    10         HttpPost httpPost = new HttpPost(url);
    11         httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
    12         
    13         StringEntity se = new StringEntity(encoderJson);
    14         se.setContentType(CONTENT_TYPE_TEXT_JSON);
    15         se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
    16         httpPost.setEntity(se);
    17         httpClient.execute(httpPost);
    18     }

    接收HTTPPost中的JSON:

     1 public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
     2         
     3         // 读取请求内容
     4         BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
     5         String line = null;
     6         StringBuilder sb = new StringBuilder();
     7         while((line = br.readLine())!=null){
     8             sb.append(line);
     9         }
    10 
    11         // 将资料解码
    12         String reqBody = sb.toString();
    13         return URLDecoder.decode(reqBody, HTTP.UTF_8);
    14     }
  • 相关阅读:
    Armijo线性搜索
    numpy 常用工具函数 —— np.bincount/np.average
    理解Buffer
    Node.js 文件系统fs模块
    NodeJS遍历文件生产文件列表
    windows 环境下node开发环境搭配问题
    npm国内镜像
    node+express实现文件上传功能
    Coding 代码管理快速入门(转)
    Node学习HTTP模块(HTTP 服务器与客户端)
  • 原文地址:https://www.cnblogs.com/wqsbk/p/5354081.html
Copyright © 2011-2022 走看看