Post请求带请求体,模拟登录获取Cookies

一、前期测试

首先用浏览器登录你需要模拟的网址,根据登录成功所获得的信息,配置模拟登录的参数:
Post请求带请求体,模拟登录获取Cookies_第1张图片

编码格式 & 参数

Post的参数是放在请求体中的,常见的编码格式有这两个:

Content-Type:application/x-www-form-urlencoded
Post请求带请求体,模拟登录获取Cookies_第2张图片
参数在:
Post请求带请求体,模拟登录获取Cookies_第3张图片
Content-Type: application/json
Post请求带请求体,模拟登录获取Cookies_第4张图片
参数在:(Json格式)
在这里插入图片描述

Postman 测试

知道编码格式和参数,用 Postman 访问测试下,看看能不能登录成功,如果 Postman 能够登录成功,那代码就能实现。如果连 Postman 测试都过不了,那代码可能也实现不了,这个网站可能存在一些验证机制。

application/x-www-form-urlencoded 参数:键值对格式
Post请求带请求体,模拟登录获取Cookies_第5张图片
application/json 参数:Json格式
Post请求带请求体,模拟登录获取Cookies_第6张图片

二、工具类

application/json

package com.xiaojian.job.util;

import net.sf.json.JSONObject;
import org.apache.http.Header;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.IOException;


public class LoginUtil {
    /**
     * 模拟登录并获取 Cookies
     * @return
     */
    public static String setCookie(String loginUrl, JSONObject jsonObject, String encoding) throws IOException {
        StringBuffer cookieStr = new StringBuffer();

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(loginUrl);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), encoding);
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");

        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Header[] headers = response.getHeaders("Set-Cookie");
        for(Header h : headers){
            cookieStr.append(h.getValue() + ";");
            System.out.println(h.getValue() + ";");
        }
        //释放链接
        response.close();
        return cookieStr.toString();
    }
}

application/x-www-form-urlencoded

package com.xiaojian.job.util;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LoginDemo {

    public static String setCookie(String loginUrl,Map<String,String> param,String encoding) throws IOException {
        StringBuffer cookieStr = new StringBuffer();
       
        // 1. 打开浏览器,创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 2.输入网址,发起post请求创建HttpPost对象
        HttpPost post = new HttpPost(loginUrl);
        post.setHeader("Content-Type","application/x-www-form-urlencoded");
        post.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");

        // 2.1 声明List集合,封装表单中的参数
        List<NameValuePair> params = new ArrayList<>();
        // 2.2 添加参数
        params.add(new BasicNameValuePair("username",param.get("username")));
        params.add(new BasicNameValuePair("password",param.get("password")));
        // 2.3 创建表单的Entity对象,对参数进行url编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,encoding);
        // 2.4 设置表单的Entity对象到Post请求中
        post.setEntity(formEntity);
        // 3.发情请求,返回响应,使用HttpClient对象发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            // 4.解析响应,获取数据
        Header[] headers = response.getHeaders("Set-Cookie");
        for(Header h : headers){
            cookieStr.append(h.getValue() + ";");
            System.out.println(h.getValue() + ";");
        }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(response != null){
                response.close();
            }
            httpClient.close();
        }
        return cookieStr.toString();
    }
}

你可能感兴趣的:(java基础,Java,EE,爬虫,postman,前端,http,cookie)