您的位置:首页 > 理论基础 > 计算机网络

httpClient发送get请求调用接口

2016-12-21 11:32 609 查看
最近在项目中需要调用外部的接口,开始用的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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息