HttpClient相关:模拟get、post请求,获取cookie,等信息

HttpClient框架

模拟发送一个get请求

package com.course.httpclient.demo;

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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;

import java.io.IOException;
import java.net.http.HttpClient;

public class myHttpClientDemo {
    @Test
    public static void myDemo() throws IOException {
        String result;
        HttpGet get = new HttpGet("http://www.baidu.com");
        CloseableHttpClient client = HttpClients.createDefault();
        //一些教程上使用的DefaultHttpClient,但是此方法已过时。
        CloseableHttpResponse response= client.execute(get);
        result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
    }
}

增加配置文件,优化参数配置

增加application.properties文件,相关url从此文件读取

application.properties:

test.url=http://localhost:8888

getCookies.url=/get/getcookie
package com.course.httpclient.cookies;

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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

public class myCookiesForGet {
    private String url;
    private ResourceBundle bundle ;

    @BeforeTest
    public  void beforeTest() {
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url");
    }
    @Test
    public  void getCookie() throws IOException {
        String result;
        String uri = bundle.getString("getCookies.url");
        HttpGet get = new HttpGet(this.url+uri);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);

    }
}

获取cookie

使用BasicCookieStore:

package com.course.httpclient.cookies;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class myCookiesForGet {
    private String url;
    private ResourceBundle bundle ;

    @BeforeTest
    public  void beforeTest() {
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url");
    }
    @Test
    public  void getCookie() throws IOException {
        String result;
        String uri = bundle.getString("getCookies.url");
        HttpGet get = new HttpGet(this.url+uri);
        BasicCookieStore store = new BasicCookieStore();
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
        CloseableHttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
        List<Cookie> cookies = store.getCookies();
        for (Cookie cookie:cookies){
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name : "+name+";"+"cookie value : "+value);
        }
    }
}

发送携带json、header、cookie的post请求

package com.course.httpclient.cookies;

import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
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.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class myCookiesForPost {
    String url;
    ResourceBundle bundle ;
    private CookieStore store;
    @BeforeTest
    public  void beforeTest() {
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url");
    }
    @Test
    public  void testGetcookies() throws IOException {
        String result;
        String uri = bundle.getString("postgetCookies.url");
        HttpPost post = new HttpPost(this.url+uri);
        this.store = new BasicCookieStore();
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
        CloseableHttpResponse response = client.execute(post);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
        System.out.println(this.store);
        List<Cookie> cookies = this.store.getCookies();
        for (Cookie cookie:cookies){
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name : "+name+";"+"cookie value : "+value);
        }
    }
    @Test(dependsOnMethods = {"testGetcookies"})
    public  void testPostMethod() throws IOException {
        //获取url
        String uri=bundle.getString("postCookiesTo.url");
        //拼接最终的测试地址
        String testUrl=this.url+uri;
        //声明一个post的方法
        HttpPost httppost=new HttpPost(testUrl);

        //添加参数
        JSONObject param = new JSONObject();
        param.put("name","hanxin");
        param.put("age","20");

        //设置请求头信息,设置header
        httppost.setHeader("Content-Type", "application/json");

        //将参数信息添加到方法中
        HttpEntity entity = new StringEntity(param.toString(), "utf-8");
        httppost.setEntity(entity);
        System.out.println(this.store);

        //声明一个client对象,用来进行方法的执行,并设置cookies信息
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(this.store).build();

        //执行post的方法并得到响应结果
        CloseableHttpResponse response3 = httpclient.execute(httppost);

        //就是判断返回结果是否符合预期
        int statusCode = response3.getStatusLine().getStatusCode();
        System.out.println("statusCode = "+ statusCode);

        String result=EntityUtils.toString(response3.getEntity(),"utf-8");;

        if (statusCode==200){
            System.out.println(result);
        } else {
            System.out.println("访问/get/with/cookies接口失败");
        }

        //将返回的响应结果字符串转化为json对象
        JSONObject resultjson = new JSONObject(result);

        //获取到结果值
        String success = (String) resultjson.get("hanxin");
        System.out.println(success);
        Assert.assertEquals("success", success);
    }
}

注:如果获取的cookie中的domain和path,和发送请求时的链接不匹配,是无法直接使用的

posted @   77的小白  阅读(367)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示