httpclient发送get,post,设置header

来源:互联网 发布:js 选中input文本 编辑:程序博客网 时间:2024/06/06 00:24

加maven依赖

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --><dependency>    <groupId>org.apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.3</version></dependency>

发送get请求

public String sendGet(String url){    String result = StringUtils.EMPTY;    CloseableHttpClient httpClient = HttpClients.createDefault();    HttpGet httpGet = new HttpGet(url);    httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");    httpGet.addHeader("Accept-Encoding", "gzip, deflate");    httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8");    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36");    httpGet.addHeader("Content-Type", "text/html; charset=UTF-8");    httpGet.addHeader("Connection", "Keep-Alive");     String host = getHost(url);    httpGet.addHeader("Host", host);    httpGet.setConfig(RequestConfig.custom().setConnectTimeout(1000).build());    try {        CloseableHttpResponse response = httpClient.execute(httpGet);        int status = response.getStatusLine().getStatusCode();        if (status == HttpStatus.SC_OK){            HttpEntity responseEntity = response.getEntity();            result = EntityUtils.toString(responseEntity, "UTF-8");        }    } catch (ClientProtocolException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    return result;}

发送post请求,以json传递参数

public String sendJsonPost(String url, JSONObject json){        String result = StringUtils.EMPTY;        CloseableHttpClient httpClient = HttpClients.createDefault();        HttpPost httpPost = new HttpPost(url);        httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");        httpPost.addHeader("Accept-Encoding", "gzip, deflate");        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.8");        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36");        httpPost.addHeader("Content-Type", "application/json");        httpPost.addHeader("Connection", "Keep-Alive");         String host = getHost(url);        httpPost.addHeader("Host", host);        StringEntity requestEntity = new StringEntity(json.toJSONString(),"utf-8");          requestEntity.setContentEncoding("UTF-8");        httpPost.setEntity(requestEntity);        try {            CloseableHttpResponse response = httpClient.execute(httpPost);            int status = response.getStatusLine().getStatusCode();            if (status == HttpStatus.SC_OK){                HttpEntity responseEntity = response.getEntity();                result = EntityUtils.toString(responseEntity, "UTF-8");            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }

发送post请求,以map传递参数

public String sendPost(String url, Map<String, Object> bodyMap){        String result = StringUtils.EMPTY;        CloseableHttpClient httpClient = HttpClients.createDefault();        HttpPost httpPost = new HttpPost(url);        httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");        httpPost.addHeader("Accept-Encoding", "gzip, deflate");        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.8");        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36");        httpPost.addHeader("Content-Type", "text/html; charset=UTF-8");        httpPost.addHeader("Connection", "Keep-Alive");         String host = getHost(url);        httpPost.addHeader("Host", host);        List<NameValuePair> bodyList = new ArrayList<NameValuePair>();        for(Entry<String, Object> entry : bodyMap.entrySet()){            bodyList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));        }        try {            httpPost.setEntity(new UrlEncodedFormEntity(bodyList, "UTF-8"));        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        }        try {            CloseableHttpResponse response = httpClient.execute(httpPost);            int status = response.getStatusLine().getStatusCode();            if (status == HttpStatus.SC_OK){                HttpEntity responseEntity = response.getEntity();                result = EntityUtils.toString(responseEntity, "UTF-8");            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }

测试

public static void main(String args[]){        HttpUtil httpUtil = new HttpUtil();        Map<String, Object> bodyMap = new HashMap<String, Object>();        String str = "";        JSONObject json = JSONObject.parseObject(str);        String result = httpUtil.sendGet("http://www.cnblogs.com/leesf456/p/4684338.html");        System.out.println(result);    }