HttpClient 的 Post 提交表单简单示例,且发现jmeter的HTTP授权管理器(HTTP Authorization Manager)可直接使用Authorization头参数替换

先看接口抓包详情:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

java代码发送这个请求的代码如下:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.5</version>
    </dependency>
package xia.wenjie;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

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

/**
 * <br>Classname: HttpClientDemo
 * <br>描述:
 * <br>功能:
 * <br>作者: 
 * <br>时间: 2021/1/23 15:48
 */

public class HttpClientDemo {
    public static void main(String[] args) throws ParseException, IOException {
        //建立NameValuePair数组,用于存储欲传送的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("grant_type", "password"));
        nvps.add(new BasicNameValuePair("username", "xxxxxxx"));
        nvps.add(new BasicNameValuePair("password", "xxxxxxx"));
        //        nvps.add(new BasicNameValuePair("", ""));
        //        nvps.add(new BasicNameValuePair("", ""));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, Consts.UTF_8);

        //初始化httpClient
        HttpClient httpClient = HttpClients.custom().build();
        //使用的请求方法
        HttpPost httpPost = new HttpPost("http://xxxxxxxxxx/api-uaa/password/token");
        httpPost.setEntity(entity);

        //请求头配置
        httpPost.setHeader("Authorization", "Basic xxxxx");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        //      httpPost.setHeader("Content-Length", "481");
        httpPost.setHeader("Host", "xxxxx.com");
        httpPost.setHeader("Accept-Encoding", "gzip");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("User-Agent", "PostmanRuntime/7.26.8");
        // 头部除了Authorization是必要的,其他的可以不要也可以请求成功,抓包有的建议加上
        HttpResponse response = null;
        try {
            //表单参数提交
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.abort();  //释放连接
        }
        System.out.println(response.getStatusLine());
        String entityString = EntityUtils.toString(response.getEntity(), "gbk"); //注意设置编码
        System.out.println(entityString);
    }

}

在这里插入图片描述

jmeter发送请求:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

jmeter 使用HTTP Authorization Manager

jmeter 应该可以不使用授权管理器,直接像java 代码设置头部
httpPost.setHeader(“Authorization”, “Basic xxxxx”);

在这里插入图片描述
测试一下也是可行的。

补充:
httpPost.setHeader(“Authorization”, “Basic xxxxx”); Basic xxxxx的值可以这样生成再设置进去也是有效的:

//   Username:Password= afxx:afxx      YWZsYzphxxx

        String auth = "afxx" + ":" + "afxx";
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        System.out.println(authHeader);

在这里插入图片描述

看阿帕奇的官网:
http://hc.apache.org/httpcomponents-client-4.5.x/examples.html

发现上面的java代码,可以不用设置头部的所有信息也是可以的:

package xia.wenjie;

/**
 * <br>Classname: ClientPreemptiveBasicAuthentication
 * <br>描述:
 * <br>功能:
 * <br>作者: xiawenjie
 * <br>时间: 2021/1/25 10:03
 */
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
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.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
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.util.ArrayList;
import java.util.List;

/**
 * An example of HttpClient can be customized to authenticate
 * preemptively using BASIC scheme.
 * <b>
 * Generally, preemptive authentication can be considered less
 * secure than a response to an authentication challenge
 * and therefore discouraged.
 */
public class ClientPreemptiveBasicAuthentication {
    //   http://testxxx.xxxx.com/api-uaa/password/token
    public static void main(String[] args) throws Exception {
        HttpHost target = new HttpHost("testxxx.xxxxx.com", 80, "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials("afxx", "afxx"));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider).build();
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            HttpPost httppost= new HttpPost("http://testxxx.xxxx.com/api-uaa/password/token");

            //建立NameValuePair数组,用于存储欲传送的参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("grant_type", "passwxxxx"));
            nvps.add(new BasicNameValuePair("username", "1311955xxxx|xxx1"));
            nvps.add(new BasicNameValuePair("password", "29ad0e3fd3db681fb9f8091c7xxxx"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, Consts.UTF_8);
            httppost.setEntity(entity);
            System.out.println("Executing request " + httppost.getRequestLine() + " to target " + target);
            for (int i = 0; i < 3; i++) {
                CloseableHttpResponse response = httpclient.execute(target, httppost, localContext);
                try {
                    System.out.println("----------------------------------------");
                    System.out.println(response.getStatusLine());
                    System.out.println(EntityUtils.toString(response.getEntity()));
                } finally {
                    response.close();
                }
            }
        } finally {
            httpclient.close();
        }
    }

}

在这里插入图片描述

CloseableHttpResponse response = httpclient.execute(target, httppost, localContext);

用 CloseableHttpResponse response = httpclient.execute(httppost, localContext); 也可以

HTTP身份认证可参考:
https://blog.csdn.net/ktlifeng/article/details/51099370

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java使用HttpClient实现POST表单发送/接收XML格式的报文,POST参数名为req的示例代码: ``` import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; 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 HttpClientExample { public static void main(String[] args) throws IOException { String url = "http://example.com/api"; String xml = "<xml><name>John</name><age>30</age></xml>"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML); httpPost.setEntity(entity); httpPost.setHeader("Content-type", "application/xml"); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println(responseString); } finally { response.close(); } } } ``` 说明: - `url`:要访问的URL地址。 - `xml`:要发送的XML格式的报文。 - `httpClient`:创建一个默认的HttpClient实例。 - `httpPost`:创建一个HttpPost实例,并将URL地址设置为请求的目标地址。 - `entity`:将XML报文封装为一个StringEntity对象,并设置内容类型为`application/xml`。 - `httpPost.setEntity(entity)`:将封装好的XML报文设置为HTTP POST请求的主体部分。 - `httpPost.setHeader("Content-type", "application/xml")`:设置请求部的内容类型为`application/xml`。 - `response`:执行HTTP POST请求,并返回一个CloseableHttpResponse实例。 - `responseEntity`:从响应中获取响应主体。 - `responseString`:将响应主体转换为字符串格式。 - `response.close()`:关闭响应实例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值