java发送http请求的两种方式:HTTPClient和CloseableHttpClient

java发送http请求有三种方式,除了原生连接方式HttpURLConnection,还有另外两种方式:HTTPClient和CloseableHttpClient
下面分别简单介绍使用HTTPClient和CloseableHTTPClient进行Get和Post请求的方式。
详情使用链接

HttpClient

使用commons-httpclient.jar,maven依赖如下:

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

简单代码如下:

private static String doGet(String url) {
    String res = null;
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(url);
    int code = 0;
    try {
        code = client.executeMethod(getMethod);
        if (code == 200) {
            res = getMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}
private static String doPost(String url, Map<String, Object> paramMap) {
    String res = null;
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        postMethod.addParameter(next.getKey(), next.getValue().toString());
    }
    try {
        int code = client.executeMethod(postMethod);
        if (code == 200) {
            res = postMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}
public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //设置传入参数的格式:请求参数是 map 的形式
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "赵云");
    paramMap.put("age", 21);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

被调用方法:
java发送http请求的两种方式:HTTPClient和CloseableHttpClient_第1张图片
测试结果:
java发送http请求的两种方式:HTTPClient和CloseableHttpClient_第2张图片
java发送http请求的两种方式:HTTPClient和CloseableHttpClient_第3张图片

CloseableHttpClient

使用httpclient.jar,maven依赖如下:

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

简单代码如下:

/**
 * 发送HttpGet请求
 * @param url
 * @return
 */
public static String doGet(String url) {
    //1.获得一个httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //2.生成一个get请求
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        //3.执行get请求并返回结果
        response = httpclient.execute(httpget);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String result = null;
    try {
        //4.处理结果,这里将结果返回为字符串
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity);
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}
/**
 * 发送HttpPost请求,参数为map
 * @param url
 * @param map
 * @return
 */
public static String doPost(String url, Map<String, Object> map) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        //给参数赋值
        formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
    }
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException e) {
        e.printStackTrace();
    }
    HttpEntity entity1 = response.getEntity();
    String result = null;
    try {
        result = EntityUtils.toString(entity1);
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //设置传入参数的格式:请求参数是 map 的形式
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "张飞");
    paramMap.put("age", 55);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

被调用方法:

java发送http请求的两种方式:HTTPClient和CloseableHttpClient_第4张图片
测试结果:
java发送http请求的两种方式:HTTPClient和CloseableHttpClient_第5张图片
java发送http请求的两种方式:HTTPClient和CloseableHttpClient_第6张图片

你可能感兴趣的:(Http,Java,java,http)