HttpClient实现get、post请求,并在发请求前进行basic auth认证

文章介绍了如何在Java中使用ApacheHttpClient库进行HTTP请求,包括GET和POST方法,并展示了如何进行基本认证。作者强调了在请求头添加基本认证信息的重要性。
摘要由CSDN通过智能技术生成

1、导入依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.46</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

2、Copy工具类

package com.wen.test.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;

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.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author 文杰
 * @version 1.0
 */
@SuppressWarnings({"all"})
public class Request {



    public static CloseableHttpClient getHttpClient() {
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // 设置BasicAuth
        CredentialsProvider provider = new BasicCredentialsProvider();
        // Create the authentication scope
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        // Create credential pair,在此处填写用户名和密码
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "12345");
        // Inject the credentials
        provider.setCredentials(scope, credentials);
        // Set the default credentials provider
        httpClientBuilder.setDefaultCredentialsProvider(provider);
        // HttpClient
        CloseableHttpClient httpClient = httpClientBuilder.build();
        return httpClient;
    }

    //GET请求
    public static String get(String url, JSONObject params) {


        CloseableHttpClient httpClient = getHttpClient();

        String sendUrl = url;

        //拼接参数
        if(Objects.nonNull(params) && params.size() > 0) {
            sendUrl = connectParams(url,params);
        }

        HttpGet httpGet = new HttpGet(sendUrl);
        httpGet.addHeader("Authorization", "Basic YWRtaW46MTIzNDU=");
        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            System.out.println(sendUrl);
            System.out.println(response.getStatusLine().getStatusCode());
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != httpEntity) {
                return EntityUtils.toString(httpEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                close(httpClient, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        throw new RuntimeException(url + "\nGet请求失败!");
    }

    //post请求
    public static String post(String url, JSONObject params, String requestBody) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String sendUrl = url;
        // 1.拼接参数
        if (Objects.nonNull(params) && params.size() > 0) {
            sendUrl = connectParams(url, params);
        }
        HttpPost httpPost = new HttpPost(sendUrl);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        CloseableHttpResponse response = null;
        try {
            // 2.设置request-body
            if (StringUtils.isNotBlank(requestBody)) {
                ByteArrayEntity entity = new ByteArrayEntity(requestBody.getBytes(StandardCharsets.UTF_8));
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != httpEntity) {
                return EntityUtils.toString(httpEntity);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                close(httpClient, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        throw new RuntimeException("调用POST请求失败!");
    }


    private static String connectParams(String url, JSONObject params) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(url).append("?");
        params.forEach((x, y) -> buffer.append(x).append("=").append(y).append("&"));
        buffer.deleteCharAt(buffer.length() - 1);
        return buffer.toString();
    }

    public static void close(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) throws IOException{
        if (null != httpClient) {
            httpClient.close();
        }
        if (null != httpResponse) {
            httpResponse.close();
        }
    }





}

说明: 使用 httpclient 进行 basic auth 认证时,69行httpGet.addHeader("Authorization", "Basic YWRtaW46MTIzNDU=");这句代码很重要!!少了这句会一直报403,本文没在 post 请求的那个方法里面去加,我这里是偷懒没加,必须加不加也403

在使用Apache HttpClient送HTTP请求时,如果需要添加认证,通常会涉及到基本认证Basic Authentication)。以下是添加基础认证的基本步骤: 1. **创建Credentials**: 首先,你需要获取用户的用户名和密码,封装成`org.apache.http.auth.UsernamePasswordCredentials`对象。例如: ```java String username = "your_username"; String password = "your_password"; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); ``` 2. **设置AuthScheme**: 创建一个`HttpHost`实例来指定你要认证的服务器地址,然后创建一个`HttpAuthenticator`设置其使用的认证方案(通常是`Scheme_BASIC`): ```java HttpHost targetHost = new HttpHost("your_host", your_port, "http"); Scheme basicAuth = new Scheme("Basic", new BasicScheme(), 80); ``` 3. **构建HttpClient**: 创建HttpClient时,通过`CloseableHttpClient`的构造函数传递`AuthScope`和`AuthState`,后者会包含你的认证信息: ```java AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); CloseableHttpClient httpClient = HttpClients.custom() .setAuthSchemes(Arrays.asList(basicAuth)) .setDefaultCredentialsProvider(new BasicCredentialsProvider()) .prepareClient(authScope) .build(); ``` 这里我们设置了默认凭证提供者,当请求时会自动将`credentials`提供给服务器。 4. **执行请求**: 现在你可以使用这个HttpClient实例来请求了,比如用`HttpGet`或`HttpPost`。记得在实际操作中关闭HttpClient资源: ```java try { HttpGet request = new HttpGet("your_resource_url"); HttpResponse response = httpClient.execute(request); // 处理响应... } finally { httpClient.close(); } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值