httpClient发送get请求调用接口

本文介绍了两种调用外部API的方法:使用HttpURLConnection与HttpClient。文章详细展示了如何配置依赖及编写代码来获取并解析响应数据。
最近在项目中需要调用外部的接口,开始用的httpurl来写,后来发现httpClient相比更简单,现在将2种方法记录下来:
    首先加入httpClient的maven依赖:
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>

通过HttpURLConnection实现:

public String getNonce(String username) {
    String url = "http://xxxxxx/lock/createNonce?name=" + username;
    JSONObject jsonObject = null;
    StringBuilder json = new StringBuilder();
    String nonce = null;
    try {
        URL getUrl = new URL(url);
        // 返回URLConnection子类的对象
        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
        // 连接
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        // 使用Reader读取输入流
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String lines;
        while ((lines = reader.readLine()) != null) {
            json.append(lines);
        }
        reader.close();
        // 断开连接
        connection.disconnect();
        //将字符串转为json格式
        jsonObject = JSONObject.fromObject(json.toString());
        nonce = jsonObject.get("nonce").toString();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return nonce;
}

HttpClient方式

public String getNonce(String username) {
    String url = "http://xxxx/lock/createNonce?name=" + username;
    JSONObject jsonObject = null;
    String nonce = null;
    //发送get请求
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            //获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String content = EntityUtils.toString(entity);
                jsonObject = JSONObject.fromObject(content);
                nonce = jsonObject.get("nonce").toString();
            }
        } finally {
            response.close();
        }
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }  finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return nonce;
}
使用 HttpClient 发送 GET 请求的实现方法如下: 1. 创建 HttpClient 对象,可使用 `HttpClients.createDefault()` 方法,示例代码如下: ```python CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 若为无参数的 GET 请求,直接使用构造方法 `HttpGet(String url)` 创建 `HttpGet` 对象;若为带参数的 GET 请求,可先使用 `URIBuilder(String url)` 创建对象,再调用 `addParameter(String param, String value)` 或 `setParameter(String param, String value)` 来设置请求参数,并调用 `build()` 方法构建一个 `URI` 对象。示例代码如下: ```java // 无参数 GET 请求 HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status"); // 带参数 GET 请求 URIBuilder uriBuilder = new URIBuilder("http://example.com"); uriBuilder.addParameter("param1", "value1"); uriBuilder.setParameter("param2", "value2"); URI uri = uriBuilder.build(); HttpGet httpGetWithParams = new HttpGet(uri); ``` 3. 创建 `HttpResponse`,调用 `HttpClient` 对象的 `execute(HttpUriRequest request)` 发送请求,该方法返回一个 `HttpResponse`。调用 `HttpResponse` 的 `getAllHeaders()`、`getHeaders(String name)` 等方法可获取服务器的响应头;调用 `HttpResponse` 的 `getEntity()` 方法可获取 `HttpEntity` 对象,该对象包装了服务器的响应内容。通过调用 `getStatusLine().getStatusCode()` 可以获取响应状态码。示例代码如下: ```java CloseableHttpResponse response = httpClient.execute(httpGet); // 获取服务器返回的状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("服务端返回成功的状态码为:" + statusCode); // 获取服务器响应头 Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println(header.getName() + ": " + header.getValue()); } // 获取服务器的响应内容 HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); System.out.println("服务端返回的数据为:" + body); ``` 4. 释放连接,关闭资源。示例代码如下: ```java response.close(); httpClient.close(); ``` 完整示例代码如下: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; 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.net.URI; import java.net.URISyntaxException; public class HttpClientGetExample { public static void main(String[] args) throws IOException, URISyntaxException { // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建请求对象 URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/user/shop/status"); uriBuilder.addParameter("param1", "value1"); URI uri = uriBuilder.build(); HttpGet httpGet = new HttpGet(uri); // 发送请求,获取响应结果 CloseableHttpResponse response = httpClient.execute(httpGet); // 获取服务器返回的状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("服务端返回成功的状态码为:" + statusCode); // 获取服务器响应头 Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println(header.getName() + ": " + header.getValue()); } // 获取服务器的响应内容 HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); System.out.println("服务端返回的数据为:" + body); // 关闭资源 response.close(); httpClient.close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值