HttpClient发送get请求,post请求,携带cookie访问,json提交

POM:

    <!-- http client-->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5</version>
    </dependency>

HttpClientUtil:

GET 设置超时时间:

    public static String doGet(String url) {
        String respContent = "";
        try {
            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
            HttpGet httpGet = new HttpGet(url);
            HttpResponse resp = client.execute(httpGet);
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                respContent = EntityUtils.toString(he, "UTF-8");
            } else {
                respContent = "Http响应异常";
            }
        } catch (Exception e) {
            LOGGER.error("HttpUtil get, err:", e);
        }
        return respContent;
    }

GET:

    public static String get(String urlNameString) {
        String result = "";
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        try {
            HttpGet get = new HttpGet(urlNameString);//这里发送get请求
            BasicClientCookie cookie = new BasicClientCookie("token", "49ba41f0-862b-4c31-add8-b07066b777d9");
            cookie.setDomain("xxx.com.cn");
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(get);
            // 判断网络连接状态码是否正常(0--200都数正常)
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

POST:

public static String post(String urlNameString, Integer id, Boolean bo) {
        String result = "";
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        try {
            StringEntity entity = new StringEntity("{\"id\":\"" + id + "\",\"enable\":" + bo + "}", "utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            HttpPost post = new HttpPost(urlNameString);//这里发送get请求
            post.setEntity(entity);

            BasicClientCookie cookie = new BasicClientCookie("token", "f9ed047d-f708-4cda-b1bc-d6abccbde576");
            cookie.setDomain("xxx.com.cn");
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(post);
            // 判断网络连接状态码是否正常(0--200都数正常)
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

Post Josn

 1     public static String httpPostWithJSON(String url) throws Exception {
 2 
 3         HttpPost httpPost = new HttpPost(url);
 4         CloseableHttpClient client = HttpClients.createDefault();
 5         String respContent = null;
 6         
 7 //        json方式
 8         JSONObject jsonParam = new JSONObject();  
 9         jsonParam.put("name", "admin");
10         jsonParam.put("pass", "123456");
11         StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题    
12         entity.setContentEncoding("UTF-8");    
13         entity.setContentType("application/json");    
14         httpPost.setEntity(entity);
15         System.out.println();
16         
17     
18 //        表单方式
19 //        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 
20 //        pairList.add(new BasicNameValuePair("name", "admin"));
21 //        pairList.add(new BasicNameValuePair("pass", "123456"));
22 //        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));   
23         
24         
25         HttpResponse resp = client.execute(httpPost);
26         if(resp.getStatusLine().getStatusCode() == 200) {
27             HttpEntity he = resp.getEntity();
28             respContent = EntityUtils.toString(he,"UTF-8");
29         }
30         return respContent;
31     }
32 

调用:

    public static void main(String[] args) throws IOException {

        //result = HttpClientUtil.get(getUrl);

        String data = "643,1839,2992,3890,3991,4002,4080,4270,4277,4333,4334,4401,4495,4501,4563,4573,4584,4653,4709,4717,4732,4766,4913,5424,5699,5705,6224,6235,6329,6342,6528,6529,6552,6555,6660,6667,6923,6970,8020,8146,8982,9354,9358,9364,9522,9554,9561,9960,10059,10188";

        doForeach(Arrays.asList(data.split(",")));
    }

    private static void doForeach(List<String> ids) {
        for (String id : ids) {
            String result = HttpClientUtil.post(postUrl, Integer.parseInt(id), true);

            System.out.println(result);
        }
    }

转载于:https://my.oschina.net/u/1000241/blog/1530219

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值