某些http请求是需要认证的,特别是一些系统直接需要进行安全交互时,往往需要基于Basic auth进行用户和秘钥等信息的传递认证。

本实例带大家基于Apache的HttpClient来进行实战演示,也算是提供给大家一个对应的工具类。

首先在pom.xml文件中引入对应的jar包依赖:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

这里还引入了fastjson,主要是用于将对象实例化成json字符串。

工具类的具体实现如下:

package com.choupangxia.httpclient;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
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.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author sec
 * @version 1.0
 * @date 2020/6/30 7:53 下午
 **/
public class HttpClientUtils {

	public static void main(String[] args) {
		String url = "https://www.choupangxia.com/";
		String username = "admin";
		String password = "admin";

		MessageVo vo = new MessageVo();
		vo.setId("No11111");
		vo.setName("Steven");
		String result = createStream(url, username, password, vo);
		System.out.println(result);
	}

	/**
	 * url: 请求的url
	 * requestDTO: post请求的url
	 * 此处根据自己需求更改为post请求还是其他请求
	 */
	private static String createStream(String url, String username, String password, MessageVo requestDTO) {
		CloseableHttpClient httpClient = getHttpClient(username, password);
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-type", "application/json; charset=utf-8");
		httpPost.setHeader("Accept", "application/json");
		String s = "";
		String s1 = JSON.toJSONString(requestDTO);
		httpPost.setEntity(new StringEntity(s1, StandardCharsets.UTF_8));
		try {
			CloseableHttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			s = EntityUtils.toString(entity);
			httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return s;
	}

	/**
	 * 获取带有权限的HttpClient连接
	 */
	private static CloseableHttpClient getHttpClient(String username, String password) {
		CredentialsProvider provider = new BasicCredentialsProvider();
		UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
		provider.setCredentials(AuthScope.ANY, credentials);
		return HttpClients.custom().setDefaultCredentialsProvider(provider).build();
	}
}

class MessageVo {
	private String id;
	private String name;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

其中关于basic auth的部分在方法getHttpClient中实现,其中创建了UsernamePasswordCredentials对象用来存储对应的秘钥信息。

通过HttpPost来设置传输文本的格式,这里是基于utf8的json格式。

注意:在使用的过程中记得当使用完之后,需要把对应的HTTPClient连接进行关闭处理。



apache httpclient 基于basic auth认证的http请求工具类插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2020/06/30/apache-httpclient-basic-auth/