您的位置:首页 > 理论基础 > 计算机网络

httpclient的基本使用代码

2018-01-09 14:55 323 查看
1.所需的依赖jar

   <dependency>

      <groupId>org.apache.httpcomponents</groupId>

      <artifactId>httpclient</artifactId>

      <version>4.5.2</version>

    </dependency>

   <!--  httpclient缓存 -->

    <dependency>

      <groupId>org.apache.httpcomponents</groupId>

      <artifactId>httpclient-cache</artifactId>

      <version>4.5</version>

    </dependency>

   <!-- http的mime类型都在这里面 -->

    <dependency>

     <groupId>org.apache.httpcomponents</groupId>

     <artifactId>httpmime</artifactId>

     <version>4.3.2</version>
    </dependency>

2.代码

package com.zy.httpclient;

import java.io.IOException;

import java.net.URI;

import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.URIBuilder;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

/**

 * httpclient工具类 

 * 封装了get post 请求方法

 * @author zl

 *

 */

public class HttpClientUtils {
/**
* 带参数的doPost请求
* @param url 请求地址
* @param map 参数
* @return 响应实体字符串
* @throws Exception 
*/
public static String doPost(String url, Map<String, String> map) {

// 使用默认配置的httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 响应
CloseableHttpResponse response = null;
String result = "";
try {
// 参数的构建
URIBuilder buildUri = new URIBuilder(url);
// 设置参数的键和值
if (map != null) {
for (String key : map.keySet()) {
buildUri.addParameter(key, map.get(key));
}
}
URI uri = buildUri.build(); // 构建uri
// 创建post实例
System.out.println(uri);
HttpPost httpPost = new HttpPost(uri);
// 执行请求 获取响应
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {// 如果请求成功
if (response.getEntity() != null) {
result = EntityUtils
.toString(response.getEntity(), "UTF-8");
}
}
} catch (Exception e) {

e.printStackTrace();
} finally {
close(response, httpclient);
}
return result;
}
/**
* 不带参数的post请求
* @param url 请求地址
* @return 
*/
public static String doPost(String url){
return doPost(url,null);
}

/**
* 带参数的get请求
* @param url 请求地址
* @param map 参数集合
* @return 响应实体
*/
public static String doGet(String url, Map<String, String> map) {

// 使用默认配置的httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 响应
CloseableHttpResponse response = null;
String result = "";
try {
// 参数的构建
URIBuilder buildUri = new URIBuilder(url);
// 设置参数的键和值
if (map != null) {
for (String key : map.keySet()) {
buildUri.addParameter(key, map.get(key));
}
}
URI uri = buildUri.build(); // 构建uri
// 创建post实例
System.out.println(uri);
HttpGet httpGet = new HttpGet(uri);
// 执行请求 获取响应
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {// 如果请求成功
if (response.getEntity() != null) {
result = EntityUtils
.toString(response.getEntity(), "UTF-8");
}
}
} catch (Exception e) {

e.printStackTrace();
} finally {
close(response, httpclient);
}
return result;
}

/**
* 不带参数的get请求
* @param url 请求地址
* @return 
*/
public static String doGet(String url){
return doGet(url,null);
}
/**
* 关闭
* @param response
* @param httpclient
*/
private static void close(CloseableHttpResponse response,
CloseableHttpClient httpclient) {
try {
if(response!=null){
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(response, httpClient);
        }

        return resultString;
    }

public static void main(String[] args) throws Exception {
/*Map<String,String> map = new HashMap<String, String>();
map.put("username", "zhangsan");
map.put("password", "123456");*/
String reslut = doGet("https://www.baidu.com");
System.out.println(reslut);
}

}

3.构建参数的另一种方式是:

// 创建Http Post请求

            HttpPost httpPost = new HttpPost(url); 

// 创建参数列表

            if (map != null) {

                List<NameValuePair> paramList = new ArrayList<>();

                for (String key : .keySet()) {

                    paramList.add(new BasicNameValuePair(key, param.get(key)));

                }

                

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");

                httpPost.setEntity(entity);

            }

// 执行http请求

            response = httpClient.execute(httpPost);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: