您的位置 首页 >  博文

httpclient模拟post请求json封装表单数据

以下代码包括最基本的GET、POST、JSON参数的POST方式的请求。(相当于POSTMAN中使用raw编写的参数)

  1package com.chinecredit.eccis.utils;
 2
 3import java.io.IOException;
 4import java.io.UnsupportedEncodingException;
 5import java.util.ArrayList;
 6import java.util.List;
 7import java.util.Map;
 8import java.util.Set;
 9
10import org.apache.http.HttpEntity;
11import org.apache.http.HttpStatus;
12import org.apache.http.NameValuePair;
13import org.apache.http.ParseException;
14import org.apache.http.client.ClientProtocolException;
15import org.apache.http.client.entity.UrlEncodedFormEntity;
16import org.apache.http.client.methods.CloseableHttpResponse;
17import org.apache.http.client.methods.HttpGet;
18import org.apache.http.client.methods.HttpPost;
19import org.apache.http.entity.StringEntity;
20import org.apache.http.impl.client.CloseableHttpClient;
21import org.apache.http.impl.client.HttpClients;
22import org.apache.http.message.BasicNameValuePair;
23import org.apache.http.util.EntityUtils;
24import org.slf4j.Logger;
25import org.slf4j.LoggerFactory;
26
27import com.alibaba.fastjson.JSONObject;
28
29/**
30 * http访问方法实现
31 * @author 王俊南 
32 * @date: 2018-11-22
33 */

34public class HttpRequestUtils {
35    private static Logger logger = LoggerFactory
36            .getLogger(HttpRequestUtils.class); // 日志记录
37
38    /**
39     * GET提交
40     * 
41     * @return
42     */

43    public static String doGet(String url) {
44        String strResult = "";
45        // 1. 创建一个默认的client实例
46        CloseableHttpClient client = HttpClients.createDefault();
47        try {
48            // 2. 创建一个httpget对象
49            HttpGet httpGet = new HttpGet(url);
50            System.out.println("executing GET request " + httpGet.getURI());
51
52            // 3. 执行GET请求并获取响应对象
53            CloseableHttpResponse resp = client.execute(httpGet);
54            try {
55                // 6. 打印响应长度和响应内容
56                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
57                    // 4. 获取响应体
58                    HttpEntity entity = resp.getEntity();
59                    System.out.println("Response content length = "
60                            + entity.getContentLength());
61                    System.out.println("------");
62                    strResult = EntityUtils.toString(resp.getEntity());
63                }
64            } finally {
65                //无论请求成功与否都要关闭resp
66                resp.close();
67            }
68        } catch (ClientProtocolException e) {
69            logger.error("get请求失败:", e);
70            // e.printStackTrace();
71        } catch (ParseException e) {
72            logger.error("get请求解析出错:", e);
73            // e.printStackTrace();
74        } catch (IOException e) {
75            logger.error("get请求IO出错:", e);
76            // e.printStackTrace();
77        } finally {
78            // 8. 最终要关闭连接,释放资源
79            try {
80                client.close();
81            } catch (Exception e) {
82                logger.error("get请求完毕关闭连接出错:", e);
83                // e.printStackTrace();
84            }
85        }
86        return strResult;
87    }
88
89    /**
90     * 普通POST提交
91     * @param url
92     * @param map
93     * @return
94     */

95    public static String doPost(String url, Map<String, Object> map) {
96        String strResult = "";
97        // 1. 获取默认的client实例
98        CloseableHttpClient client = HttpClients.createDefault();
99        // 2. 创建httppost实例
100        HttpPost httpPost = new HttpPost(url);
101        // 3. 创建参数队列(键值对列表)
102        List<NameValuePair> paramPairs = new ArrayList<>();
103        Set<String> keySet = map.keySet();
104        for (String key : keySet) {
105            Object val = map.get(key);
106            paramPairs.add(new BasicNameValuePair(key, val.toString()));
107        }
108        UrlEncodedFormEntity entity;
109        try {
110            // 4. 将参数设置到entity对象中
111            entity = new UrlEncodedFormEntity(paramPairs, "UTF-8");
112            // 5. 将entity对象设置到httppost对象中
113            httpPost.setEntity(entity);
114            // 6. 发送请求并回去响应
115            CloseableHttpResponse resp = client.execute(httpPost);
116            try {
117                // 7. 获取响应entity
118                HttpEntity respEntity = resp.getEntity();
119                strResult = EntityUtils.toString(respEntity, "UTF-8");
120            } finally {
121                // 9. 关闭响应对象
122                resp.close();
123            }
124
125        } catch (ClientProtocolException e) {
126            e.printStackTrace();
127        } catch (UnsupportedEncodingException e) {
128            e.printStackTrace();
129        } catch (IOException e) {
130            e.printStackTrace();
131        } finally {
132            // 10. 关闭连接,释放资源
133            try {
134                client.close();
135            } catch (Exception e) {
136                e.printStackTrace();
137            }
138        }
139        return strResult;
140    }
141
142    /**
143     * json参数方式POST提交
144     * @param url
145     * @param params
146     * @return
147     */

148    public static String doPost(String url, JSONObject params){
149        String strResult = "";
150        // 1. 获取默认的client实例
151        CloseableHttpClient client = HttpClients.createDefault();
152        // 2. 创建httppost实例
153        HttpPost httpPost = new HttpPost(url);
154        httpPost.addHeader("Content-Type""application/json;charset=utf-8"); //添加请求头
155        try {
156            httpPost.setEntity(new StringEntity(params.toJSONString(),"utf-8"));
157            CloseableHttpResponse resp = client.execute(httpPost);
158            try {
159                // 7. 获取响应entity
160                HttpEntity respEntity = resp.getEntity();
161                strResult = EntityUtils.toString(respEntity, "UTF-8");
162            } finally {
163                resp.close();
164            }
165        } catch (ClientProtocolException e) {
166            e.printStackTrace();
167        } catch (UnsupportedEncodingException e) {
168            e.printStackTrace();
169        } catch (IOException e) {
170            e.printStackTrace();
171        } finally {
172            try {
173                client.close();
174            } catch (Exception e) {
175                e.printStackTrace();
176            }
177        }
178        return strResult;
179    }
180}


关于作者: 王俊南(Jonas)

昨夜寒蛩不住鸣。惊回千里梦,已三更。起来独自绕阶行。人悄悄,帘外月胧明。 白首为功名。旧山松竹老,阻归程。欲将心事付瑶琴。知音少,弦断有谁听。

热门文章