java调用http接口get请求
时间: 2023-04-05 13:02:38 浏览: 103
java http请求
可以使用Java中的HttpURLConnection或者HttpClient库来发送GET请求,具体实现可以参考以下代码:
使用HttpURLConnection:
```
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
```
使用HttpClient:
```
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
response.close();
httpClient.close();
```
阅读全文