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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

JavaPOST请求设置请求头,格式为`application/json`,要求返回JSON包体,可以使用多种方式来实现,常见的有使用`HttpURLConnection`、`Apache HttpClient`或者Java 11引入的`java.net.http.HttpClient`。以下是使用`java.net.http.HttpClient`作为示例来实现这一功能的方法: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; import java.util.Base64; public class HttpPostRequest { public static void main(String[] args) { String targetURL = "http://example.com/api/resource"; // 替换为目标服务器的URL String jsonInputString = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; // JSON格式的请求体数据 HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(targetURL)) .header("Content-Type", "application/json") .header("Authorization", getBasicAuthHeader("username", "password")) .POST(HttpRequest.BodyPublishers.ofString(jsonInputString)) .build(); client.sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join(); // 等待异步操作完成 } private static String getBasicAuthHeader(String username, String password) { String credentials = username + ":" + password; return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); } } ``` 在这个示例中,首先创建了一个`HttpClient`实例,然后构建了一个`HttpRequest`对象,设置了请求类型为POST添加了相应的请求头和请求体。请求头中设置了`Content-Type`为`application/json`以指明送的数据格式,以及`Authorization`头用于提供基本认证信息。这里使用了`getBasicAuthHeader`方法来生成基本认证的Base64编码字符串。 之后,使用`client.sendAsync`方法异步请求通过`thenApply`和`thenAccept`来处理响应。最后通过`join()`方法等待异步操作完成。 需要注意的是,由于网络请求涉及到网络环境和服务器状态,实际应用中需要处理可能出现的异常情况,例如超时、网络中断等,且在生产环境中,应该使用合适的线程模型来管理这些异步操作,以避免阻塞主线程或者造成资源浪费。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值