OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比

时间:2023-03-08 17:05:32

1.HttpURLConnection

 public class HttpURLConnectionGetAndPost {
private String urlAddress = "xxxx"; public void doGet(String method, String s) throws IOException {
String getUrl = urlAddress + method + "?sex=" + s; URL url = new URL(getUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
StringBuffer sb = new StringBuffer();
InputStream in = httpURLConnection.getInputStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
String readLine = ""; while ((readLine = bufferReader.readLine()) != null) {
sb.append(readLine);
}
in.close();
bufferReader.close();
httpURLConnection.disconnect(); Log.d("test", sb.toString()); } else {
Log.d("test", "get failed");
} } public void doPost(String method, String s) throws IOException { URL url = new URL(urlAddress + method);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("content-type", "");
httpURLConnection.setRequestProperty("content-type", "");
httpURLConnection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); String content = "sex=" + s; dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close(); if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = "";
StringBuffer sb = new StringBuffer();
while ((readLine = bufferedReader.readLine()) != null) {
sb.append(readLine);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.d("test", sb.toString());
} else {
Log.d("test", "post failed");
}
}
}

2.HttpClient

 public class HttpClientGetAndPost {
private String urlAddress = "xxxx";
private void doGet(String method, String s){ String getUrl = urlAddress+ method + "?sex= "+ s;
HttpGet httpGet = new HttpGet(getUrl);
try {
HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() ==200){
String result = EntityUtils.toString(httpResponse.getEntity());
Log.d("test","result="+result);
}else{ Log.d("test","get failed");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /// HttpPost
} private void doPost(String method, String s) throws ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost(urlAddress+method);
List<NameValuePair> parms = new ArrayList<NameValuePair>();
parms.add(new BasicNameValuePair("sex",s) );
httpPost.setEntity(new UrlEncodedFormEntity(parms,HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() ==200){
String result = EntityUtils.toString(httpResponse.getEntity());
Log.d("test","result="+result);
}else{ Log.d("test","post failed");
}
}
}

3. OKHttp3

 public class OkHttpGetAndPost {

 private String urlAddress = "xxxx";
private OkHttpClient okHttpClient = new OkHttpClient(); private void doGet(String method, String s) throws IOException {
String url = urlAddress + method + "?sex=" + s;
Request request = new Request.Builder().url(url).get().build();
Response respone = okHttpClient.newCall(request).execute();
if (respone.isSuccessful()) {
Log.d("test", respone.body().string());
} else {
Log.d("test", "get failed");
}
} private void doPost(String method, String s) {
FormBody formBody = new FormBody.Builder().add("sex", s).build();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"sex\",\""+s+"\"}");
Request request = new Request.Builder().url(urlAddress + method).post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
Log.d("test", arg1.body().string());
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.d("test", "post failed");
}
});
}
}

由以上demo可以看出,OKHttp使用最简单方便,代码书写量少,而且网络请求高效。

如果喜欢作者的文章,请关注"写代码的猿"订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载.

OKHttp源码学习--HttpURLConnection  HttpClient OKHttp Get and post Demo用法对比