最近在项目中需要调用外部的接口,开始用的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);
HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
String lines;
while ((lines = reader.readLine()) != null) {
json.append(lines);
}
reader.close();
connection.disconnect();
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;
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;
}