httpClient发送get请求调用接口

最近在项目中需要调用外部的接口,开始用的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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值