相关jar包和POST引入一致:
public static JSONObject httpGet(String url) throws OApiException {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().
setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig);
try {
response = httpClient.execute(httpGet, new BasicHttpContext());
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
+ ", url=" + url);
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
JSONObject result = JSON.parseObject(resultStr);
if (result.getInteger("errcode") == 0) {
// result.remove("errcode");
// result.remove("errmsg");
return result;
} else {
System.out.println("request url=" + url + ",return value=");
System.out.println(resultStr);
int errCode = result.getInteger("errcode");
String errMsg = result.getString("errmsg");
throw new OApiException(errCode, errMsg);
}
}
} catch (IOException e) {
System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}