转载自:原文链接:https://blog.csdn.net/qq_40697725/article/details/106480225
HttpURLConnection
JDK 自带的 HttpURLConnection 标准库,是一个多用途、轻量级的http客户端。它对网络请求的封装没有HttpClient彻底,api比较简单,用起来没有那么方便。但是正是由于此,使得我们能更容易的扩展和优化的HttpURLConnection。HttpURLConnection继承URLConnection,底层socket,最原始通信,使用 HttpURLConnection 发起 HTTP 请求最大的优点是不需要引入额外的依赖。但无法提供额外的功能。
get请求示例:
public static String sendGet(String urlString)throws Exception{
String resp ="";
URL url = new URL(urlString);
//得到connection对象。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//连接
connection.connect();
//得到响应码
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//得到响应流
InputStream inputStream = connection.getInputStream();
//将响应流转换成字符串
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream, "utf-8"));
final StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
resp = stringBuffer.toString();
}
return resp;
}
post请求示例:
public static String sendPost(String urlString,String params)throws Exception{
URL url = new URL(urlString);
//得到connection对象。
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(10*1000);
httpURLConnection.setReadTimeout(10*1000);
//连接
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(params.getBytes("utf-8"));
//获取内容
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
final StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String resp = stringBuffer.toString();
//关闭流
if (stringBuffer!=null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resp;
}
HttpClient
HttpClient是apache的一个项目,封装了很多底层细节。HttpClient 是Apache的一个三方网络框架,网络请求做了完善的封装,api众多,用起来比较方便,开发快。实现比较稳定,bug比较少,但是正式由于其api众多,是我们很难再不破坏兼容性的情况下对其进行扩展。
get请求示例
public static String httpGet(String url) throws IOException {
String result = "";
//创建HttpClient对象
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
//发送get请求
HttpResponse response = httpClient.execute(httpGet);
//请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
result = EntityUtils.toString(response.getEntity());
System.out.println(result);
return result;
}
return result;
}
post请求示例
public static String httpPost(String url, String jsonParam) throws IOException {
String result = "";
//创建HttpClient对象
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (jsonParam != null) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
//发送post请求
HttpResponse response = httpClient.execute(httpPost);
//请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
result = EntityUtils.toString(response.getEntity());
System.out.print(result);
return new String(result.getBytes("ISO-8859-1"), "UTF-8");
}
return result;
}
OkHttp
OkHttp 接口设计友好,支持 HTTP/2,并且在弱网和无网环境下有自动检测和恢复机制,因此,是当前 Android APP 开发中使用最广泛的 HTTP clilent lib 之一。OkHttp 是 Square 公司开源的针对 Java 和 Android 程序,封装的一个高性能 http 请求库。
get 请求示例
public static String sendGet(String url)throws Exception {
//创建OkHttp客户端
OkHttpClient okHttpClient = new OkHttpClient();
//构建请求
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
//执行获取响应
Response response = call.execute();
System.out.println(response.body().string());
return response.body().string();
}
post请求示例:
public static String sendPost(String url)throws Exception {
//创建OkHttp客户端
OkHttpClient okHttpClient = new OkHttpClient();
//创建请求对象
RequestBody body = new FormBody.Builder()
.add("键", "值")
.add("键", "值").build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
//执行获取响应
Response response = call.execute();
System.out.println(response.body().string());
return response.body().string();
}
如果表单是个json:
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "你的json");
如果数据包含文件:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
.build();