HttpClient

一、初识HttpClient

HttpClient 是Apache Jakarta Common 下的子项目可以用来提供高效的、最新的、功能丰富支持 HTTP 协议客户端编程工具包,并且它支持 HTTP 协议最新版本建议

—-百度百科

就是用来发送http请求或者解析http响应的。

二、HttpClient请求

当然在使用之前,需要导包,使用maven(不使用maven就要自己取下jar包,apache官网就有):

<dependency&gt;
    <groupId&gt;org.apache.httpcomponents</groupId&gt;
    <artifactId&gt;httpclient</artifactId&gt;
    <version&gt;4.5.13</version>
</dependency>

导入之后,一般分为六步

  1. 创建HttpClient实例
  2. 创建某种连接方法实例
  3. 调用HttpClient实例execute方法执行请求方法
  4. 读取response
  5. 释放连接,无论执行方法是否成功

2.1 GET请求

我们先以GET请求为例

  1. 创建HttpClient实例

    CloseableHttpClient httpClient = HttpClients.createDefault();
    
  2. 创建GET请求方法实例

    HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    
  3. 调用HttpClient实例执行GET实例,返回response

    CloseableHttpResponse response = httpClient.execute(httpGet);
    
  4. 解析response

    // 获取状态
    int status = response.getStatusLine().getStatusCode();
    // 获取实例
    HttpEntity entity = response.getEntity();
    // 获取html
    String html = EntityUtils.toString(entity);
    
  5. 释放连接

    response.close();
    httpClient.close();
    

完整代码

package vip.yangsf;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DecompressingHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import sun.plugin.dom.html.HTMLDocument;

import java.io.IOException;

public class GetTest {
    public static void main(String[] args) throws IOException {
        // 1. 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2. 创建GET请求方法实例
        HttpGet httpGet = new HttpGet("http://test.yangsf.vip");
        // 3. 调用HttpClient实例来执行GET请求方法,得到response
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 4. 读response,判断是否访问成功 2xx表示 成功。
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 &amp;&amp; status < 300) {
            // 对得到后的实例可以进行处理例如读取回复体,读取html
            HttpEntity entity = response.getEntity();
            System.out.println(response);
            System.out.println("=======================");
            String html = EntityUtils.toString(entity);
            System.out.println(html);
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }

        // 6. 释放连接
        response.close();
        httpClient.close();
    }
}

2.2 POST请求

步骤基本上一模一样,只不过可以设置post带上参数

httpPost.setEntity(new StringEntity("this is Post"));

package vip.yangsf;

import com.sun.xml.internal.ws.api.pipe.ContentType;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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;

import java.io.IOException;

public class PostTest {
        public static void main(String... args) throws IOException {
            // 1. 创建HttpClient实例
            CloseableHttpClient httpclient = HttpClients.createDefault();

            // 2. 创建HttpPost实例
            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            httpPost.setEntity(new StringEntity("this is Post"));

            // 3. 调用HttpClient实例来执行HttpPost实例
            CloseableHttpResponse response = httpclient.execute(httpPost);
            // 4. 读 response
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                System.out.println(response);
                System.out.println("===================");
                String html = EntityUtils.toString(entity);
                System.out.println(html);
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
            // 5. 释放连接
            response.close();
            httpclient.close();
        }
}

效果

在这里插入图片描述

其他请求方法比如putdelete等也是大同小异。

三、HttpClient提交表单

提交表单一共就这几步:

  1. 创建http实例
  2. 创建Post请求
  3. 设置表单参数并让Post携带
  4. 执行请求,获取响应
  5. 解析响应
  6. 关闭资源
package vip.yangsf;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FormSubmitTest {
    public static void main(String[] args) throws IOException {
        // 1. 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 2. 设置表单参数
        List<NameValuePair> kv =  new ArrayList<>();
        kv.add(new BasicNameValuePair("name", "root"));
        kv.add(new BasicNameValuePair("password", "123456"));

        // 3. 创建HttpPost实例
        HttpPost httpPost = new HttpPost("http://httpbin.org/post");

        // 4. 让Post携带表单参数
        httpPost.setEntity(new UrlEncodedFormEntity(kv, Consts.UTF_8));

        // 5. 获取HttpResponse响应
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 6. 读response
        System.out.println(EntityUtils.toString(response.getEntity()));

        // 7. 释放资源
        response.close();
        httpClient.close();
    }
}

结果

在这里插入图片描述

HttpClient最基本用法就是这些。之后可以官方文档查阅更多的用法比如HttpClient还可以获取证书上传文件等等。

原文地址:https://blog.csdn.net/yangsf_/article/details/124527687

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_37306.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注