Android系統(tǒng)提供了兩種HTTP通信類(lèi),HttpURLConnection
和HttpClient
。
改則網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,改則網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為改則上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢(qián),請(qǐng)找那個(gè)售后服務(wù)好的改則做網(wǎng)站的公司定做!
盡管Google在大部分安卓版本中推薦使用HttpURLConnection,但是這個(gè)類(lèi)相比HttpClient實(shí)在是太難用,太弱爆了。
OkHttp是一個(gè)相對(duì)成熟的解決方案,據(jù)說(shuō)Android4.4的源碼中可以看到HttpURLConnection已經(jīng)替換成OkHttp實(shí)現(xiàn)了。所以我們更有理由相信OkHttp的強(qiáng)大。
使用范圍
OkHttp支持Android 2.3及其以上版本。
對(duì)于Java, JDK1.7以上。
基本使用
HTTP GET
OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } }
Request是OkHttp中訪問(wèn)的請(qǐng)求,Builder是輔助類(lèi)。Response即OkHttp中的響應(yīng)。
Response類(lèi):
public boolean isSuccessful() Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.
response.body()
返回ResponseBody
類(lèi)
可以方便的獲取string
public final String string() throws IOException Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8. Throws: IOException
當(dāng)然也能獲取到流的形式:
public final InputStream byteStream()
HTTP POST
POST提交Json數(shù)據(jù)
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); f (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } }
使用Request
的post
方法來(lái)提交請(qǐng)求體RequestBody
POST提交鍵值對(duì)
很多時(shí)候我們會(huì)需要通過(guò)POST方式把鍵值對(duì)數(shù)據(jù)傳送到服務(wù)器。 OkHttp提供了很方便的方式來(lái)做這件事情。
OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody formBody = new FormEncodingBuilder() .add("platform", "android") .add("name", "bug") .add("subject", "XXXXXXXXXXXXXXX") .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } }
注意:
import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import cn.wiz.sdk.constant.WizConstant; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; public class OkHttpUtil { private static final OkHttpClient mOkHttpClient = new OkHttpClient(); static{ mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS); } /** * 該不會(huì)開(kāi)啟異步線程。 * @param request * @return * @throws IOException */ public static Response execute(Request request) throws IOException{ return mOkHttpClient.newCall(request).execute(); } /** * 開(kāi)啟異步線程訪問(wèn)網(wǎng)絡(luò) * @param request * @param responseCallback */ public static void enqueue(Request request, Callback responseCallback){ mOkHttpClient.newCall(request).enqueue(responseCallback); } /** * 開(kāi)啟異步線程訪問(wèn)網(wǎng)絡(luò), 且不在意返回結(jié)果(實(shí)現(xiàn)空callback) * @param request */ public static void enqueue(Request request){ mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onResponse(Response arg0) throws IOException { } @Override public void onFailure(Request arg0, IOException arg1) { } }); } public static String getStringFromServer(String url) throws IOException{ Request request = new Request.Builder().url(url).build(); Response response = execute(request); if (response.isSuccessful()) { String responseUrl = response.body().string(); return responseUrl; } else { throw new IOException("Unexpected code " + response); } } private static final String CHARSET_NAME = "UTF-8"; /** * 這里使用了HttpClinet的API。只是為了方便 * @param params * @return */ public static String formatParams(List<BasicNameValuePair> params){ return URLEncodedUtils.format(params, CHARSET_NAME); } /** * 為HttpGet 的 url 方便的添加多個(gè)name value 參數(shù)。 * @param url * @param params * @return */ public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){ return url + "?" + formatParams(params); } /** * 為HttpGet 的 url 方便的添加1個(gè)name value 參數(shù)。 * @param url * @param name * @param value * @return */ public static String attachHttpGetParam(String url, String name, String value){ return url + "?" + name + "=" + value; } }
總結(jié)
通過(guò)上面的例子我們可以發(fā)現(xiàn),OkHttp在很多時(shí)候使用都是很方便的,而且很多代碼也有重復(fù),因此特地整理了下面的工具類(lèi)。
分享標(biāo)題:AndroidOkHttp基本使用詳解
URL地址:http://m.kartarina.com/article20/jecsco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、自適應(yīng)網(wǎng)站、小程序開(kāi)發(fā)、網(wǎng)頁(yè)設(shè)計(jì)公司、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)