java发送网络请求的方法
时间: 2023-11-04 10:08:14 浏览: 139
在Java中,发送网络请求可以使用Java的内置库HttpURLConnection或者第三方库如OkHttp和Apache HttpClient。
以下是使用HttpURLConnection发送网络请求的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com/path/to/resource");
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();
// Print result
System.out.println(response.toString());
}
}
```
这个示例使用了HttpURLConnection来创建一个GET请求,并且打印了响应代码和响应体。你可以修改请求方法和请求体来发送不同类型的请求。
使用OkHttp发送网络请求的示例代码:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.example.com/path/to/resource")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
```
这个示例使用了OkHttp库来创建一个GET请求,并且打印了响应体。你可以按照需要修改请求方法和请求体来发送不同类型的请求。
使用Apache HttpClient发送网络请求的示例代码:
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://www.example.com/path/to/resource");
HttpResponse response = client.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
}
```
这个示例使用了Apache HttpClient库来创建一个GET请求,并且打印了响应体。你可以按照需要修改请求方法和请求体来发送不同类型的请求。
阅读全文