码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient发送Json数据到指定接口

时间:2018-01-06 20:05:58      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:error   return   utils   gen   cli   log   ade   url   response   

项目中遇到将Json数据发送到指定接口,于是结合网上利用HttpClient进行发送.

    /**
     * post发送json数据
     * @param url
     * @param param
     * @return
     */
    private String doPost(String url, JSONObject param) {
        HttpPost httpPost = null;
        String result = null;
        try {
            HttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                httpPost.setEntity(se); // post方法中,加入json数据
                httpPost.setHeader("Content-Type", "application/json");
            }
            
            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
            
        } catch (Exception ex) {
            logger.error("发送到接口出错", ex);
        }
        return result;
    }

 

HttpClient发送Json数据到指定接口

标签:error   return   utils   gen   cli   log   ade   url   response   

原文地址:https://www.cnblogs.com/fxust/p/8214998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!