httpClient使用Post Get Put Delete请求

Post请求(常用的)

public  String sendDefaultHttpsPost(String url, Map paramMap) throws IOException{
        List nvPairs = new ArrayList();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse httpResponse = null;
        String retStr = "";
        CloseableHttpClient httpClient = null;
        try {
            if(paramMap!=null){
                for (Map.Entry entry : paramMap.entrySet()) {
                    nvPairs.add(new BasicNameValuePair(entry.getKey(),
                            (entry.getValue().toString() == null ? "" : entry.getValue().toString())));
                }
            }
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(config);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            httpPost.setEntity(new UrlEncodedFormEntity(nvPairs, "UTF-8"));
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 302) {// 302重定向,获取http头中重定向地址
                retStr = httpResponse.getLastHeader("Location").getValue();
            } else {
                retStr = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            retStr = "远程连接异常";
            e.printStackTrace();
        } finally {
            if (nvPairs != null) {
                nvPairs = null;
            }
            if (httpPost != null) {
                httpPost.abort();
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return retStr;
    }

Psot请求(multipart/form-data;)

public static String postAPI(Mapmap,String url,String cookie) throws Exception{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        String boundary ="------WebKitFormBoundaryMAj7ABMLt3aJpmGH";
        try {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
                httpPost.setHeader("Cookie", cookie);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(Charset.forName("UTF-8"));
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.setBoundary(boundary);
                for(Entry entry:map.entrySet()){
                    builder.addTextBody(entry.getKey(),entry.getValue().toString(),ContentType.create("text/plain", Consts.UTF_8));
                }
                //HttpEntity
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
                // 执行提交
                HttpResponse response = httpClient.execute(httpPost);
                //响应
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                        // 将响应内容转换为字符串
                        result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                }
        } catch (Exception e) {
                e.printStackTrace();
        } finally {
            httpClient.close();
        }
        return result;
        
        
    }

Get请求

 public static String getApi(String url,String cookie) throws Exception{
         CloseableHttpClient httpClient = HttpClients.createDefault();
         CloseableHttpResponse response = null;
         HttpGet httpGet = new HttpGet(url);
         httpGet.setHeader("Content-type", "application/json");
         httpGet.setHeader("Cookie", cookie);
         String retStr=null;
         try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 302) {// 302重定向,获取http头中重定向地址
                retStr = response.getLastHeader("Location").getValue();
            } else {
                retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            response.close();
        }
        return retStr;
    }

Put请求

 public static String putApi(Mapmap,String url,String cookie) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        String boundary ="------WebKitFormBoundaryMAj7ABMLt3aJpmGH";
        try {
                HttpPut httpPut=new HttpPut(url);
                httpPut.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
                httpPut.setHeader("Cookie", cookie);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(Charset.forName("UTF-8"));
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.setBoundary(boundary);
                for(Entry entry:map.entrySet()){
  builder.addTextBody(entry.getKey(),entry.getValue().toString(),ContentType.create("text/plain", Consts.UTF_8));
                }
                //HttpEntity
                HttpEntity entity = builder.build();
                httpPut.setEntity(entity);
                // 执行提交
                HttpResponse response = httpClient.execute(httpPut);
                //响应
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                        // 将响应内容转换为字符串
                        result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                }
        } catch (Exception e) {
                e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

Delete请求

    public static class HttpMyDelete extends HttpEntityEnclosingRequestBase {
        public final static String METHOD_NAME = "DELETE";
        public HttpMyDelete() {
            super();
        }
        public HttpMyDelete(final URI uri) {
            super();
            setURI(uri);
        }
        public HttpMyDelete(final String uri) {
            super();
            setURI(URI.create(uri));
        }
        @Override
        public String getMethod() {
            return METHOD_NAME;
        }
    }

 

public static String deleteApi(String jsonStr,String url,String cookie) {
         CloseableHttpClient httpClient = HttpClients.createDefault();
         HttpMyDelete httpdelete = new HttpMyDelete(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
            httpdelete.setConfig(requestConfig);
            httpdelete.setHeader("Content-type", "application/json");
            httpdelete.setHeader("DataEncoding", "UTF-8");
            httpdelete.setHeader("Cookie", cookie);
            CloseableHttpResponse httpResponse = null;
            try {
                httpdelete.setEntity(new StringEntity(jsonStr));
                httpResponse = httpClient.execute(httpdelete);
                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                return result;
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (httpResponse != null) {
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值