httpclient发送Get请求和Post请求

创建HttpClient发送请求、接收响应

    • Get请求简介
      • get无参数
      • get有参数
    • Post请求简介
      • post携带JSON参数
      • post携带表单参数
    • postman自动生成OKhttp代码

Get请求简介

  • 1). 创建HttpClient对象,可以使用HttpClients.createDefault()
  • 2). 如果是无参数的GET请求,则直接使用构造方法HttpGet(String url)创建HttpGet对象即可;
  • 3)如果是带参数GET请求,则可以先使用URIBuilder(String url)创建对象,再调用addParameter(Stringparam, String value)`, 或setParameter(String param, String)
    value)来设置请求参数,并调用build()方法构建一个URI对象。
  • 4). 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest
    request)发送请求,该方法返回一个HttpResponse。调用HttpResponse的getAllHeaders()、getHeaders(String
    name)等方法可获取服务器的响应头;
  • 5)调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()可以获取响应状态码。
  • 6). 释放连接。

构建一个Maven项目,引入如下依赖

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

get无参数

如果是无参数的GET请求,则直接使用构造方法HttpGet(String url)创建HttpGet对象即可

/**
 *普通的GET请求
 */
public class DoGET {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                //请求体内容
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\baidu.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            //相当于关闭浏览器
            httpclient.close();
        }
    }
}

get有参数

如果是带参数GET请求,则可以先使用URIBuilder(String url)创建对象,再调用addParameter(Stringparam, String value)

public class HttpclientTest {
    @Test
    public void httpGet() throws IOException {
        // 1.创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2. 创建HttpGet,设置URL访问地址
        String urlTest = "https://XXXX/XXX/shopping/platformInfo?platformid=7";
        HttpGet httpGet = new HttpGet(urlTest);
        // 3. 请求执行,获取响应
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //解析响应
        if (response.getStatusLine().getStatusCode() == 2000) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(content.length());
        }
        // 4.获取响应实体
        HttpEntity entity = response.getEntity();
        System.out.println(EntityUtils.toString(entity, "utf-8"));
        response.close();
        httpClient.close();
    }

代码中使用的是公司接口,请求URL前缀就XXX表示了,get请求如图所示
运行结果:我们已经看到get接口成功返回一条数据
httpclient发送Get请求和Post请求_第1张图片

Post请求简介

  • 1). 创建HttpClient对象,可以使用HttpClients.createDefault();
  • 2). 如果是无参数的POST请求,则直接使用构造方法HttpPost(String url)创建HttpPost对象即可;
  • 3)如果是带参数POST请求,先构建HttpEntity对象并设置请求参数,然后调用setEntity(HttpEntityentity)创建HttpPost对象。
  • 4). 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest
    request)发送请求,该方法返回一个HttpResponse。调用HttpResponse的getAllHeaders()、getHeaders(String
    name)等方法可获取服务器的响应头;
  • 5)调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()可以获取响应状态码。
  • 6). 释放连接。

post携带JSON参数

如果是带JSON参数POST请求,先构建HttpEntity对象并设置请求参数,因为我们的参数是JSON格式的,需要将请求对象转换成string类型的,然后调用setEntity(HttpEntityentity)创建HttpPost对象
首先我们先创建一个请求实体类PostData,代码如图所示

/**
 * @param
 * @author wcy
 * @create 2022/10/15
 * @return
 * @description
 **/
public class PostData {
    private String categoryid;
    private int currentPage;
    private String end_time;
    private int pageSize;
    private int platformid;
    private String start_time;
    private int step_id;

    public String getCategoryid() {
        return categoryid;
    }

    public void setCategoryid(String categoryid) {
        this.categoryid = categoryid;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public String getEnd_time() {
        return end_time;
    }

    public void setEnd_time(String end_time) {
        this.end_time = end_time;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPlatformid() {
        return platformid;
    }

    public void setPlatformid(int platformid) {
        this.platformid = platformid;
    }

    public String getStart_time() {
        return start_time;
    }

    public void setStart_time(String start_time) {
        this.start_time = start_time;
    }

    public int getStep_id() {
        return step_id;
    }

    public void setStep_id(int step_id) {
        this.step_id = step_id;
    }
}
  @Test
    public void httpPost() throws IOException {
        // 1.创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//         2.创建post对象,设置URL访问地址
        String url = "https://XxX/XxX/shopping/goodsRank";
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            PostData data = new PostData();
            data.setCategoryid("");
            data.setCurrentPage(1);
            data.setEnd_time("2022-11-02");
            data.setPageSize(20);
            data.setPlatformid(1);
            data.setStart_time("2022-11-02");
            data.setStep_id(464);
            String bodyEntity = JSON.toJSONString(data);
            HttpEntity entity = new StringEntity(bodyEntity, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);
            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取响应数据
                entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity, "utf-8"));
            }
        }catch (IOException e){
           e.printStackTrace();
        }
   }

运行结果:
httpclient发送Get请求和Post请求_第2张图片

post携带表单参数

post请求传递参数的形式是将参数放入表单请求体中,然后将表单对象放入请求体中传递。

//1.获得一个httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.生成一个post请求
HttpPost httpPost = new HttpPost("http://www.baidu.com/");
//3.请求参数添加到请求体中,表单提交
List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(key, val));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, charset);
httpPost.setEntity(formEntity);
//4.执行get请求并返回结果
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
    //5.处理结果响应体
    HttpEntity entity = response.getEntity();
} finally {
    response.close();
}

postman自动生成OKhttp代码

首先在postman编写好post请求的URL,请求参数,请求方式,请求头
httpclient发送Get请求和Post请求_第3张图片
点击sends按钮右侧的code弹窗展示,如图所示
httpclient发送Get请求和Post请求_第4张图片
框里面的代码就是自动生成的,我们可以复制代码到idea中,需要在maven`装下OKhhtp的依赖
官网连接:https://mvnrepository.com/

     OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("categoryid","")
                .addFormDataPart("currentPage","1")
                .addFormDataPart("end_time ","2022-11-01")
                .addFormDataPart("pageSize","20")
                .addFormDataPart("platformid ","1")
                .addFormDataPart("start_time ","2022-11-01")
                .addFormDataPart("step_id ","464")
                .build();
        Request request = new Request.Builder()
                .url("https://XXX/XXX/shopping/goodsRank")
                .method("POST", body)
                .addHeader("Cookie", "laravel_session=eyJpdiI6IkRxcWx6M201UHRWMWFWeDY3b0RURmc9PSIsInZhbHVlIjoid0pSM241cmgvRUk5WndHTnc2azlzNFpHVDh6MCt5R1pSV21pQXRPRDB1eEpyMThNZVUrelRKYzJHSVUzNHp3T290RHppOVNvSFZ3Z2VCQ2g4SEFQUjBXSGpRL3VkcUJiRUFzRGc5b21BRnhOUUwzUkNENlhzUEJlVGtWZkhZNGoiLCJtYWMiOiIyYzM1NDhkYzQ0YmZiNjQ5OWIwZjg1NDA3NTYxZTcyM2IyODAxNWI1ZGU4NmEzOTE2YjRmOTBjYzQzMzUyNjY1In0%3D")
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response);
    }

OKhttp的语法跟httpclient差不多,都是http工具类

你可能感兴趣的:(Java接口自动化,java,服务器,servlet)