在Java中使用6种方法进行http请求
Java 中发出 HTTP 请求的常见方法有:
- Java SE 的 HttpURLConnection 类
- Apache 的 HttpClient 第三方库
- Spring 的 RestTemplate 类
- JavaFX 的 WebEngine 类
- OkHttp 第三方库
- Retrofit 第三方库
以上列举的方法都是可以用来发出 HTTP 请求的,具体的使用方法参考如下
也可以参考官方文档和代码示例。
- Java SE 的 HttpURLConnection 类:
import java.io.*;
import java.net.*;
public class HttpRequestExample {
public static void main(String[] args.html) throws IOException {
URL url = new URL("https://www.example.com".html);
HttpURLConnection con = (HttpURLConnection.html) url.openConnection();
con.setRequestMethod("GET".html);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream(.html)));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine(.html)) != null) {
content.append(inputLine.html);
}
in.close();
con.disconnect();
System.out.println(content.html);
}
}- Apache 的 HttpClient 第三方库:
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("http://www.example.com".html);
CloseableHttpResponse response = client.execute(request.html);- Spring 的 RestTemplate 类:
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://www.example.com", String.class);- JavaFX 的 WebEngine 类:
WebEngine engine = new WebEngine();
engine.load("http://www.example.com".html);- OkHttp 第三方库:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.com".html)
.build();
Response response = client.newCall(request.html).execute();- Retrofit 第三方库:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.example.com".html)
.build();
MyApi api = retrofit.create(MyApi.class);
Call<ResponseBody> call = api.getData();
Response<ResponseBody> response = call.execute();以上是常见的 Java 中发出 HTTP 请求的方法以及具体的示例,实际应用中可以根据需要选择适合的方法。
版权声明:本文为原创文章,版权归 戴老师的博客 所有,转载请联系博主获得授权。
本文地址:https://tushu.info/archives/archives-zai-Java-zhong-shi-yong-6-zhong-fang-fa.html
如果对本文有什么问题或疑问都可以在评论区留言,我看到后会尽量解答。