java 发起get请求
时间: 2023-10-15 20:25:25 浏览: 118
java发起http请求获取返回的Json对象方法
在Java中,可以使用HTTPClient或HttpURLConnection来发起GET请求。HTTPClient是一个第三方开源框架,对HTTP请求进行了很好的封装,而HttpURLConnection是Java的标准请求方式。下面是使用这两种方式发起GET请求的方法:
1. 使用HTTPClient:
- 首先,需要导入HTTPClient的相关包,比如Apache的HttpClient 4.5.5。
- 创建HttpClient对象,并创建HttpGet请求对象,设置请求的URL。
- 执行请求,获取响应结果。
- 通过HttpResponse对象获取响应状态码、响应头和响应体等信息。
示例代码如下所示:
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://example.com/api");
try {
HttpResponse response = httpClient.execute(httpGet);
// 处理响应结果
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用HttpURLConnection:
- 创建URL对象,设置请求的URL。
- 打开URLConnection连接,并设置请求方法为GET。
- 获取输入流,读取响应结果。
- 关闭连接。
示例代码如下所示:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应结果
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上是使用Java发起GET请求的两种实现方法,可以根据具体需求选择适合的方式进行开发。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [java发起http请求获取返回的Json对象方法](https://download.csdn.net/download/weixin_38747025/12957986)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [JAVA发送GET和POST请求](https://blog.csdn.net/sunyanchun/article/details/128392329)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文