首页 > Web开发 > 详细

HttpClient发送Json数据到指定接口

时间:2018-01-06 19:47:23      阅读:299      评论:0      收藏:0      [点我收藏+]

项目中遇到将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数据到指定接口

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

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