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
            putMethod.setRequestHeader("Authorization",
                    "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            /* 允许put请求开启认证 */
            putMethod.setDoAuthentication(true);
        }
        // 如果需要其他头信息可以继续添加

        // 设置请求体为JSON
        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();
            }
            putMethod.setRequestEntity(requestEntity);
        }

        String response = "";
        /* 执行 HTTP put 请求 */
        try {
            int statusCode = httpClient.executeMethod(putMethod);
            /* 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("请求出错: " + putMethod.getStatusLine());
            }
            /* 处理 HTTP 响应内容 */
            // HTTP响应头部信息,这里简单打印
            Header[] headers = putMethod.getResponseHeaders();
            for (Header h : headers) {
                System.out.println(h.getName() + "\t------------> " + h.getValue());
            }
            // 获取返回的流
            InputStream inputStream = putMethod.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 {
            /* 释放连接 */
            putMethod.releaseConnection();
        }
        return response;
    }

    public static String doDelete(String urlStr){
        return doDeleteByBasicAuth(urlStr, null, null);
    }

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

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

        /* 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        /* 生成 GetMethod 对象并设置参数 */
        DeleteMethod deleteMethod = new DeleteMethod(urlStr);
        // 设置 put 请求超时为 5 秒
        deleteMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理,用的是默认的重试处理:请求三次
        deleteMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

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

        if (null != username && null != password) {
            // Base64加密方式认证方式下的basic auth
            deleteMethod.setRequestHeader("Authorization",
                    "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            /* 允许delete请求开启认证 */
            deleteMethod.setDoAuthentication(true);
        }
        // 如果需要其他头信息可以继续添加

        String response = "";
        /* 执行 HTTP put 请求 */
        try {
            int statusCode = httpClient.executeMethod(deleteMethod);
            /* 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("请求出错: " + deleteMethod.getStatusLine());
            }
            /* 处理 HTTP 响应内容 */
            // HTTP响应头部信息,这里简单打印
            Header[] headers = deleteMethod.getResponseHeaders();
            for (Header h : headers) {
                System.out.println(h.getName() + "\t------------> " + h.getValue());
            }
            // 获取返回的流
            InputStream inputStream =  deleteMethod.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 {
            /* 释放连接 */
            deleteMethod.releaseConnection();
        }
        return response;
    }
}

2、调用方法

RestMock.doGetByBasicAuth("http://localhost:8081/api/v4", "admin", "public");
System.out.println();
		
RestMock.doPostByBasicAuth("http://localhost:8081/api/v4/data/export","admin", "public");
System.out.println();
		
RestMock.doPutByBasicAuth("http://localhost:8081/api/v4/nodes/emqx@127.0.0.1/plugins/emqx_telemetry/reload", "admin", "public");
System.out.println();
		
RestMock.doDeleteByBasicAuth("http://localhost:8081/api/v4/topic-metrics", "admin", "public");
System.out.println();
### 回答1: 使用Java调用HTTP接口的步骤如下: 1. 创建一个URL对象,指定HTTP接口的地址。 2. 打开URL连接,获取URLConnection对象。 3. 设置URLConnection对象的请求方式、超时时间等参数。 4. 发送请求,并获取服务器返回的响应结果。 5. 处理响应结果,可以将响应结果转换成字符串或其他格式。 下面是一个简单的示例代码,演示如何使用Java调用HTTP接口: ```java import java.net.*; import java.io.*; public class HttpDemo { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); if (conn.getResponseCode() != 200) { throw new RuntimeException("HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } } ``` 上面的代码使用Java的URLConnection类实现了一个简单的HTTP GET请求,并将响应结果输出到控制台。如果需要发送POST请求,可以使用URLConnection的setRequestMethod方法设置为POST,并调用URLConnection的getOutputStream方法向服务器发送请求数据。 ### 回答2: 使用Java调用HTTP接口的主要步骤如下: 1. 导入相关的类库:首先需要在Java项目中导入相关的类库,如java.net包下的URL、HttpURLConnection类等。 2. 构建URL对象:根据需要调用的HTTP接口地址,使用URL类的构造方法创建URL对象。例如,可以通过URL url = new URL("http://www.example.com/api")创建一个指向接口地址的URL对象。 3. 打开连接:通过调用URL对象的openConnection()方法,打开URL连接。这将返回一个URLConnection对象。 4. 设置请求参数:如果需要传递请求参数,可以通过调用URLConnection对象的setRequestMethod()方法设置HTTP请求方法,例如GET或POST。可以通过调用URLConnection对象的setRequestProperty()方法设置请求头参数,例如Content-Type,Authorization等。 5. 发送请求:如果是GET请求,可以直接调用URLConnection对象的connect()方法发送请求。如果是POST请求,可以先获取URLConnection对象的OutputStream,并通过写入输出流的方式发送请求参数,然后再调用connect()方法发送请求。 6. 获取响应:通过调用URLConnection对象的getResponseCode()方法获取HTTP响应的状态码,以判断请求是否成功。可以通过调用URLConnection对象的getInputStream()方法获取HTTP响应的输入流,以获取响应数据。 7. 处理响应:根据接口的具体响应数据格式,可以使用Java提供的相关类库(如JSON解析库)对响应数据进行解析和处理。 8. 关闭连接:使用完毕后,需要调用URLConnection对象的disconnect()方法关闭连接。 注意事项: - 如果接口需要进行身份认证,可以在请求头中添加Authorization参数,例如使用Basic Auth或Token等方式。 - 使用HTTPS协议时,需要进行SSL证书验证。 - 在处理大量请求时,可能需要考虑使用连接池来提高性能和资源利用率。 总结:通过以上步骤,我们可以使用Java来调用HTTP接口,发送请求并处理响应,实现与其他系统进行数据交互。 ### 回答3: 使用Java调用http接口可以通过Java的网络编程功能来实现。Java提供了许多类和方法来实现http请求和接收http响应。 首先,我们可以使用Java的URL类来创建一个URL对象,指定要访问的http接口的地址。然后,我们可以使用URLConnection类的openConnection()方法打开该URL连接,并将其转换为HttpURLConnection对象。 接下来,我们可以设置HttpURLConnection对象的请求方法(GET、POST、PUT、DELETE等),设置请求头部信息(如Content-Type、Authorization等),并通过setDoOutput()方法将请求数据写入连接。 然后,我们可以使用HttpURLConnection的getOutputStream()方法获取输出流,将请求数据写入流中。如果是GET请求,可以通过HttpURLConnection的getInputStream()方法获取输入流,读取服务器的响应数据。 最后,我们可以使用BufferedReader类逐行读取服务器的响应数据,并保存在一个字符串中,或按照其它需要进行处理。 在处理http响应数据时,我们可以使用Java提供的第三方库,如Apache HttpClient和OkHttp,它们封装了更多的功能和便捷的方法,使用起来更加方便。 总的来说,使用Java调用http接口需要一些基本的编程知识和网络编程相关的类和方法。通过对Java网络编程的学习和使用,我们可以轻松地实现与http接口的交互,并处理接口返回的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菠萝蚊鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值