duansky'weblog

统计

留言簿(3)

友情链接

阅读排行榜

评论排行榜

用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);
    }

posted on 2012-03-18 16:21 duansky 阅读(13953) 评论(5)  编辑  收藏 所属分类: Java

评论

# re: 用httpPost对JSON发送和接收的例子[未登录] 2015-07-15 16:24 aaa

请告诉博主,他很帅!  回复  更多评论   

# 1212 2015-10-23 07:57 1212

请告诉博主,他很帅!  回复  更多评论   

# re: 用httpPost对JSON发送和接收的例子[未登录] 2015-12-11 12:20 1

请告诉博主,他很帅!  回复  更多评论   

# re: 用httpPost对JSON发送和接收的例子 2016-02-10 10:08 zj

需要导入哪些jar包,可以给个地址吗?谢谢谢谢。。。  回复  更多评论   

# re: 用httpPost对JSON发送和接收的例子 2016-08-01 17:29 请告诉博主,他很帅!

请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!请告诉博主,他很帅!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: