//java发送get请求,并带上参数,需要导入jar包,pom.xml在下方,参数拼接在?后面即可
public static String send_Get(String url){
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = null;
String data = "";
try {
// uriBuilder = new URIBuilder("http://localhost.....");
uriBuilder = new URIBuilder(url);
HttpGet httpGet = new HttpGet(uriBuilder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
System.out.println(entity.getContent());
if (entity != null) {
// return it as a String
String json_result = EntityUtils.toString(entity);
System.out.println(json_result);
// JSONObject jsonObject = JSONObject.parseObject(json_result);
// if (jsonObject.containsKey("code") && jsonObject.get("code").toString().equals("1")){
// data = jsonObject.get("data").toString();
// System.out.println(data);
// }
}
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}finally {
// closeHTTP();
if (uriBuilder != null){
uriBuilder.clearParameters();
}
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data;
}
如果需要在Header中带参数,请参考这个方法:
在pom.xml中导入jar包(版本可根据自己情况定):
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.1.0</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
public static String httpGet(String url , String param , String token){
// 获取连接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse=null;
String finalString = null;
HttpGet httpGet = new HttpGet(url);
/**公共参数添加至httpGet*/
/**header中通用属性*/
httpGet.setHeader("User-Agent","bobo");
httpGet.setHeader("Authorization",token);
// httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Content-Type", "application/json");
try {
httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
finalString= EntityUtils.toString(entity, "UTF-8");
try {
httpResponse.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return finalString;
}
}