基於okhttp的非同步請求

來源:互聯網
上載者:User

標籤:

抽空封裝了一下基於okHttp的網路請求,剛剛封裝好get,post, download,upload請求,不需要建立線程,支援Json自動轉換 。

Get和Post(檔案上傳也屬於Post)主要分倆個步驟:

    1.通過HttpRequestBuilder來建立請求實體物件。

    2.通過HttpUtil的sendRequest方法來發送請求,並且使用ResultCallBack來接受返回內容,這個步驟中成功時,自動將json轉換為實體,若失敗會執行ResultCallBack的onError 方法,並傳遞HttpException,這個對象中包含http錯誤碼,比如404,500等。 

get請求方式:

    

private void getSample() {HttpRequest request = new HttpRequestBuilder().url(url).addHeader("cookie", "df").addParams("key", "value").method(HttpMethod.GET).build();HttpUtil.getInstance().sendRequest(request, new ResultCallBack<Result>() {@Overridepublic void onResponse(Result response) {// TODO Auto-generated method stubtextView.setText(response.getData().getName());}@Overridepublic void onError(Request request, HttpException httpException) {// TODO Auto-generated method stubtextView.setText("requestCode:"+httpException.getResponseCode()+"  ErrorMessage:"+httpException.getMessage());}});}

post請求:

    

private void postSample() {HttpRequest request = new HttpRequestBuilder().url("http://www.oschina.net/action/user/hash_login").addHeader("cookie", "df").addParams("email", "xxxxxxxxx").addParams("pwd", "xxxxxxxxxxxxxxxxx").method(HttpMethod.POST).build();HttpUtil.getInstance().sendRequest(request,new ResultCallBack<String>() {@Overridepublic void onError(Request request,HttpException httpException) {// TODO Auto-generated method stub}@Overridepublic void onResponse(String response) {// TODO Auto-generated method stubtextView.setText(response);}});}


檔案上傳:

    

private void fileUploadSample() {if (!TextUtils.isEmpty(textView.getText())) {File file = new File(textView.getText().toString());final String url = "伺服器位址。。。";HttpRequest request = new HttpRequestBuilder().url(url).method(HttpMethod.POST).addFile(new FileDiscription(file).setUploadPrograssListener(fileUploadListener)).build();HttpUtil.getInstance().sendRequest(request,new ResultCallBack<String>() {@Overridepublic void onError(Request request,HttpException httpException) {// TODO Auto-generated method stub}@Overridepublic void onResponse(String response) {// TODO Auto-generated method stubtextView.setText(response);}});}}


檔案下載是Get請求,只不過沒有使用ResultCallBack而是使用了DownloadCallBack,可以監聽下載進度,有完成和失敗的回調。代碼如下:

 

private void downLoad(){HttpRequest request= new HttpRequestBuilder().url("http://img.taopic.com/uploads/allimg/130501/240451-13050106450911.jpg").method(HttpMethod.GET).downLoadPath(filePath, String.valueOf(new Date().getTime())+".jpg").build();HttpUtil.getInstance().downLoad(request, new DownLoadCallBack() {@Overridepublic void onDownLoading(int prograss) {// TODO Auto-generated method stubtextView.setText(prograss+"%");progressBar.setProgress(prograss);}@Overridepublic void onDownLoadSuccess() {// TODO Auto-generated method stubtextView.setText("down load success");}@Overridepublic void onDownLoadFail(HttpException ex) {// TODO Auto-generated method stubtextView.setText(ex.getMessage());}});}

源碼地址:

    https://github.com/YounMario/HttpDemo

基於okhttp的非同步請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.