三种方法的差异
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.append(new String(temp, 0, readLen, "UTF-8"));
}

本文介绍了Android开发中三种常用的网络访问方式:HttpURLConnection、Volley和okhttp3,详细阐述了它们的主要差异,包括同步与异步支持情况以及WebSocket的兼容性。同时,提供了各个方法的使用示例,并提醒在Android Studio中使用okhttp3需要注意的相关依赖问题。
最低0.47元/天 解锁文章
9975

被折叠的 条评论
为什么被折叠?



