首页 > Web开发 > 详细

用httpPost对JSON发送和接收的例子

时间:2015-08-02 19:36:58      阅读:1079      评论:0      收藏:0      [点我收藏+]

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);
技术分享    }

用httpPost对JSON发送和接收的例子

原文:http://www.cnblogs.com/yidaxia/p/4696480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!