HttpClient发送Json数据到指定接口

项目中遇到将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;
    }

 

posted @ 2018-01-06 18:56  疯狂的蜗牛仔  阅读(10100)  评论(0编辑  收藏  举报