三种方法的差异
HttpURLConnection、和okhttp3是Android最常用的三种网络方式,其主要差别是:
1、HttpURLConnection为同步的方式,Volley只支持异步的方法,而okhttp3同时支持同步和异步的方法。
2、HttpURLConnection与Volley不支持WebSocket,而okhttp3是支持的。
同步的网络访问方式不能在主线程中使用,必须通过其它线程或者AsyncTask来使用。
HttpURLConnection的使用方式
HttpURLConnection通过同步方法来访问网络,具体可参考如下代码:
public static String doPost(String path, Map params) {
Log.d(LOGTAG,"URL:" + path);
String result = null;
InputStream is = null;
HttpURLConnection conn = null;
URL url = null;
try{
url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
//conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Accept", "application/json");
conn.connect();
//Send post params
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
String postParas = JSONObject.wrap(params).toString();
Log.d(LOGTAG, "POST:" + postParas);
dos.write(postParas.getBytes("UTF-8"));
dos.flush();
dos.close();
int code = conn.getResponseCode();
StringBuilder builder = new StringBuilder ();
if(code == HttpURLConnection.HTTP_OK) {
//get response
is = conn.getInputStream();
byte[] temp = new byte[1024];
int readLen = 0;
if( (readLen = is.read(temp)) != -1) {
builder.appen