1、我們需要添加兩個第三方jar包
httpclient-4.5.2.jar
httpcore-4.4.4.jar
2、下面是部分示例代碼
public String getCurrentNum(){
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
String strURL = "訪問服務器的地址";
HttpGet httpget = new HttpGet(strURL);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("request url : " + strURL);
if (entity != null) {
String strContent = EntityUtils.toString(entity);
EntityUtils.consume(entity);
System.out.println("response content:" + strContent);
return strContent;
}
} finally {
response.close();
}
}catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}