HTTP Basic Auth 的 POST / GET / PUT / DELETE 请求 By Java

Posted 菠萝蚊鸭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTP Basic Auth 的 POST / GET / PUT / DELETE 请求 By Java相关的知识,希望对你有一定的参考价值。

HTTP Basic Auth 的 POST / GET / PUT 请求 By Java

一、依赖

jar 包:
commons-httpclient-3.1.jar
commons-codec-1.15.jar
commons-logging-1.1.1.jar

Maven 依赖:

<dependency>
	<groupId>commons-httpclient</groupId>
	<artifactId>commons-httpclient</artifactId>
	<version>3.1</version>
</dependency>

二、代码

1、RestMock 工具类

package com;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * @author wxhntmy
 * 网络请求类
 */
public class RestMock<K, V> 

    /**
     * post请求
     *
     * @param urlStr url
     * @return 响应信息
     */
    public static String doPost(String urlStr) 
        return doPostByBasicAuth(urlStr, null, null, null);
    

    /**
     * 带请求体的post方法
     *
     * @param urlStr   url
     * @param sendData 请求体数据,json格式
     * @return 响应信息
     */
    public static String doPost(String urlStr, JSONObject sendData) 
        return doPostByBasicAuth(urlStr, sendData, null, null);
    

    /**
     * 带BASIC认证的http post请求
     *
     * @param urlStr   http请求的地址,例如:http://localhost:8081/api/v4/data/export
     * @param username basic认证的用户名
     * @param password basic认证的密码
     * @return 响应信息
     */
    public static String doPostByBasicAuth(String urlStr, String username, String password) 
        return doPostByBasicAuth(urlStr, null, username, password);
    

    /**
     * 带BASIC认证的http post请求
     *
     * @param urlStr   http请求的地址,例如:http://localhost:8081/api/v4/data/export
     * @param sendData 请求体,这里要求json对象
     * @param username basic认证的用户名
     * @param password basic认证的密码
     * @return 响应信息
     */
    public static String doPostByBasicAuth(String urlStr, JSONObject sendData, String username, String password) 

        System.out.println("url------> " + urlStr);

        String response = "";

        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(urlStr);

        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        // 设置请求头 Content-Type
        postMethod.setRequestHeader("Content-Type", "application/json");
        // 如果需要其他头信息可以继续添加

        if (null != username && null != password) 
            // Base64加密方式认证方式下的basic auth
            postMethod.setRequestHeader("Authorization",
                    "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            /* 允许请求开启认证 */
            postMethod.setDoAuthentication(true);
        

        System.out.println("Request-Method\\t------------> " + postMethod.getName());

        if (null != sendData) 
            // 设置请求体为JSON
            RequestEntity requestEntity = null;
            try 
                requestEntity = new StringRequestEntity(sendData.toString(), "application/json", "UTF-8");
             catch (UnsupportedEncodingException e1) 
                // TODO 自动生成的 catch 块
                System.out.println("----------请求体编码失败:" + e1.getMessage());
                e1.printStackTrace();
            
            postMethod.setRequestEntity(requestEntity);
        

        // 设置 请求超时为 5 秒
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理,用的是默认的重试处理:请求三次
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        /* 执行 HTTP POST 请求 */
        try 
            int statusCode = httpClient.executeMethod(postMethod);
            /* 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) 
                System.out.println("请求出错: " + postMethod.getStatusLine());
            
            /* 处理 HTTP 响应内容 */
            // HTTP响应头部信息,这里简单打印
            Header[] headers = postMethod.getResponseHeaders();
            for (Header h : headers) 
                System.out.println(h.getName() + "\\t------------> " + h.getValue());
            
            // 获取返回的流
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            BufferedReader br;
            StringBuilder buffer = new StringBuilder();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String temp;
            while ((temp = br.readLine()) != null) 
                buffer.append(temp);
            
            response = buffer.toString();

            br.close();
            inputStream.close();
            System.out.println("----------response:" + response);

         catch (HttpException e) 
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
         catch (IOException e) 
            // 发生网络异常
            System.out.println("发生网络异常!");
            e.printStackTrace();
         finally 
            /* 释放连接 */
            postMethod.releaseConnection();
        

        return response;
    

    /**
     * get 请求
     *
     * @param urlStr urlStr
     * @return 响应信息
     */
    public static String doGet(String urlStr) 
        return doGetByBasicAuth(urlStr, null, null);
    

    /**
     * 把map转换成get url上的参数,?key=value&key=value
     *
     * @param parameter map
     * @return 参数字符串
     */
    private static String generateDoGetRequestParameter(Map<String, String> parameter) 
        StringBuilder queryString = new StringBuilder();
        if (parameter.isEmpty()) 
            System.out.println("参数列表为空,生成get请求参数失败!");
            return queryString.toString();
        
        int j = 0;
        for (String key : parameter.keySet()) 
            String value = parameter.get(key);
            //最后一个参数末尾不需要&
            if (j == (parameter.keySet().size() - 1)) 
                queryString.append(key).append("=").append(value);
             else 
                queryString.append(key).append("=").append(value).append("&");
            
            j++;
        
        return queryString.toString();
    

    /**
     * get 请求
     *
     * @param urlStr    urlStr
     * @param parameter 请求参数
     * @return 响应信息
     */
    public static String doGet(String urlStr, Map<String, String> parameter) 
        System.out.println("url------> " + urlStr);
        if ("/".equals(urlStr.substring(urlStr.length() - 1))) 
            urlStr = urlStr.substring(0, urlStr.length() - 1);
        
        urlStr = urlStr + "?" + generateDoGetRequestParameter(parameter);
        return doGetByBasicAuth(urlStr, null, null);
    

    /**
     * 带BASIC认证的http get请求
     *
     * @param urlStr   http请求的地址,例如:http://localhost:8081/api/v4
     * @param username basic认证的用户名
     * @param password basic认证的密码
     * @return 响应信息
     */
    public static String doGetByBasicAuth(String urlStr, String username, String password) 

        System.out.println("url------> " + urlStr);

        /* 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        /* 生成 GetMethod 对象并设置参数 */
        GetMethod getMethod = new GetMethod(urlStr);
        // 设置请求头 Content-Type
        getMethod.setRequestHeader("Content-Type", "application/json");
        // 如果需要其他头信息可以继续添加

        if (null != username && null != password) 
            // Base64加密方式认证方式下的basic auth
            getMethod.setRequestHeader("Authorization",
                    "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            /* 允许get请求开启认证 */
            getMethod.setDoAuthentication(true);
        

        System.out.println("Request-Method\\t------------> " + getMethod.getName());

        // 设置 get 请求超时为 5 秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String response = "";
        /* 执行 HTTP GET 请求 */
        try 
            int statusCode = httpClient.executeMethod(getMethod);
            /* 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) 
                System.out.println("请求出错: " + getMethod.getStatusLine());
            
            /* 处理 HTTP 响应内容 */
            // HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for (Header h : headers) 
                System.out.println(h.getName() + "\\t------------> " + h.getValue());
            
            // 获取返回的流
            InputStream inputStream = getMethod.getResponseBodyAsStream();
            BufferedReader br;
            StringBuilder buffer = new StringBuilder();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String temp;
            while ((temp = br.readLine()) != null) 
                buffer.append(temp);
            
            response = buffer.toString();

            br.close();
            inputStream.close();
            System.out.println("----------response:" + response);
         catch (HttpException e) 
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
         catch (IOException e) 
            // 发生网络异常
            System.out.println("发生网络异常!");
            e.printStackTrace();
         finally 
            /* 释放连接 */
            getMethod.releaseConnection();
        
        return response;
    

    /**
     * put请求
     *
     * @param urlStr url
     * @return 响应信息
     */
    public static String doPut(String urlStr) 

        return doPutByBasicAuth(urlStr, null, null, null);
    

    /**
     * put请求
     *
     * @param urlStr   url
     * @param sendData 请求体 JSON
     * @return 响应信息
     */
    public static String doPut(String urlStr, JSONObject sendData) 

        return doPutByBasicAuth(urlStr, sendData, null, null);
    

    /**
     * 带BASIC认证的http put请求
     *
     * @param urlStr   http请求的地址,例如:http://localhost:8081/api/v4/nodes/emqx@127.0.0.1/plugins/emqx_telemetry/load
     * @param username basic认证的用户名
     * @param password basic认证的密码
     * @return 响应信息
     */
    public static String doPutByBasicAuth(String urlStr, String username, String password) 
        return doPutByBasicAuth(urlStr, null, username, password);
    

    /**
     * 带BASIC认证的http put请求
     *
     * @param urlStr   http请求的地址,例如:http://localhost:8081/api/v4/nodes/emqx@127.0.0.1/plugins/emqx_telemetry/load
     * @param sendData 待发送的数据 json
     * @param username basic认证的用户名
     * @param password basic认证的密码
     * @return 响应信息
     */
    public static String doPutByBasicAuth(String urlStr, JSONObject sendData, String username, String password) 

        System.out.println("url------> " + urlStr);

        /* 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        /* 生成 GetMethod 对象并设置参数 */
        PutMethod putMethod = new PutMethod(urlStr);
        // 设置 put 请求超时为 5 秒
        putMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理,用的是默认的重试处理:请求三次
        putMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        System.out.println("Request-Method\\t------------> " + putMethod.getName());

        if (null != username && null != password) 
            // Base64加密方式认证方式下的basic auth
        

以上是关于HTTP Basic Auth 的 POST / GET / PUT / DELETE 请求 By Java的主要内容,如果未能解决你的问题,请参考以下文章

HTTP Basic Auth 的 POST / GET / PUT / DELETE 请求 By Java

C# 采用Basic Auth传递Post或者GET 数据

nginx认证模块ngx_http_auth_basic_module

Nginx实现基于用户的访问控制(Ngx_http_auth_basic_module模块)

Nginx实现基于用户的访问控制(Ngx_http_auth_basic_module模块)

HTTP 基本认证(basic auth)和摘要认证(digest auth)区别