HTTP/1.1 200 Content-Type:application/json;charset=utf-8 Content-Length:<content data lenght> <content data> 如何用java代码实现这个http请求
时间: 2024-06-08 21:11:10 浏览: 123
可以使用Java中的HttpURLConnection类来实现这个HTTP请求。示例代码如下:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法和请求头
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 发送请求
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,url变量为请求的URL地址,connection变量为HttpURLConnection实例,通过设置请求方法和请求头来发送GET请求。最后通过读取响应的方式获取服务器返回的数据。
阅读全文