程序员在开发工作中,进行接口开发的时候,常常用到http请求。今天小编就介绍四个进行http请求的框架。
import java.net.*;
import java.io.*;
public class HttpURLConnectionExample {
private static HttpURLConnection con;
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(content.toString());
}
}
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("https://www.example.com");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
System.out.println(result);
} finally {
response.close();
}
}
}
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class OkhttpExample {
private static final OkHttpClient client = new OkHttpClient();
public static void main(String[] args) throws IOException {
Request request = new Request.builder()
.url("https://www.example.com")
.build();
try (Response response = client.newCall(request).execute()) {
String result = response.body().string();
System.out.println(result);
}
}
}
public class HttpTemplate {
public static String httpGet(String url) {
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
return result;
}
public static String httpPost(String url, String name) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForEntity(url, name, String.class).getBody();
}
public static void main(String str[]) {
System.out.println(HttpTemplate.httpGet("https://www.example.com"));
System.out.println(HttpTemplate.httpPost("https://www.example.com", "ming"));
}
}
微信扫码加好友
全部评论