概述
1、加入对okhttp的依赖
在app的build.gradle当中的
dependencies{
}标签中加入依赖
compile 'com.squareup.okhttp3:okhttp:3.3.1'
2、okhttpclient3、http get(同步)client = new OkHttpClient();
需要新建立一个子线程,对于超过1MB的响应body,应使用流的方式来处理body。
private void syncGet() { new Thread() { @Override public void run() { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Call call = client.newCall(request); try { Response response = call.execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { Log.d(TAG, responseHeaders.name(i) + ": " + responseHeaders.value(i)); } Log.d(TAG, "body===>" + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
结果:4、异步http get
private void asynchronousGet() { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { Log.d(TAG, responseHeaders.name(i) + "=====> " + responseHeaders.value(i)); } Log.d(TAG, "body===>" + response.body().string()); } }); }
结果:
5、提取响应头
private void getresponseHeader() { new Thread() { @Override public void run() { Request request = new Request.Builder() .url("https://api.github.com/repos/square/okhttp/issues") .header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json; q=0.5") .addHeader("Accept", "application/vnd.github.v3+json") .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Log.d(TAG, "Server: " + response.header("Server")); Log.d(TAG, "Date: " + response.header("Date")); Log.d(TAG, "Vary: " + response.headers("Vary")); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
结果:
07-04 11:49:25.644 4300-4340/com.example.okhttpdemo D/MainActivity: Server: GitHub.com 07-04 11:49:25.644 4300-4340/com.example.okhttpdemo D/MainActivity: Date: Tue, 04 Jul 2017 03:49:23 GMT 07-04 11:49:25.644 4300-4340/com.example.okhttpdemo D/MainActivity: Vary: [Accept, Accept-Encoding, Accept-Encoding]
6、http post提交String
private void postString() { new Thread() { @Override public void run() { String postBody = "" + "Releasesn" + "--------n" + "n" + " * _1.0_ May 6, 2013n" + " * _1.1_ June 15, 2013n" + " * _1.2_ August 11, 2013n"; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)) .build(); Call call = client.newCall(request); Response response = null; try { response = call.execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Log.d(TAG, "body====>" + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
结果:
7、post stream
private void postStream() { new Thread() { @Override public void run() { RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_MARKDOWN; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("Numbersn"); sink.writeUtf8("-------n"); for (int i = 2; i <= 997; i++) { sink.writeUtf8(String.format(" * %s = %sn", i, factor(i))); } } private String factor(int n) { for (int i = 2; i < n; i++) { int x = n / i; if (x * i == n) return factor(x) + " × " + i; } return Integer.toString(n); } }; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Log.d(TAG, "body--->" + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
结果:
8、post file
我在android手机根目录下放置了一个file.txt文件,文件里面的内容是123456
打印结果:private void postFile() { new Thread() { @Override public void run() { File file = new File("/mnt/sdacard/360sicheck.txt"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Log.d(TAG, "body===>" + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
07-04 13:42:27.510 25669-25794/com.example.okhttpdemo D/MainActivity: body===><p>123456</p>
9、post提交表单
private void postForm() { new Thread() { @Override public void run() { RequestBody formBody = new FormBody.Builder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Log.d(TAG, "body===>" + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
打印结果:
07-04 13:50:17.949 1822-2120/com.example.okhttpdemo D/MainActivity: body===><!DOCTYPE html> <html class="client-nojs" lang="en" dir="ltr"> <head> <meta charset="UTF-8"/> <title>Jurassic Park - Wikipedia</title> <script>document.documentElement.className = document.documentElement.className.replace( /(^|s)client-nojs(s|$)/, "$1client-js$2" );</script> <script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"Jurassic_Park","wgTitle":"Jurassic Park","wgCurRevisionId":788361236,"wgRevisionId":788361236,"wgArticleId":11056991,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Pages using citations with format and no URL","Wikipedia indefinitely move-protected pages","Use mdy dates from June 2011","Wikipedia articles needing clarification from May 2016","English-language films","Jurassic Park","Dinosaurs in fiction","Film series introduced in 1993","Films set in amusement parks","Universal Studios franchises","Cloning in fiction","Genetic engineering in fiction","Science fiction films by series","Techno-thriller films","Amusement parks in fiction","Films adapted into video games","Films adapted into comics","Book series introduced in 1989","American book series","American film series"],"wgBreakFrames":false,"wgPageContentLanguage":"en","wgPageContentModel":"wikitext","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"dmy","wgMonthNames":["","January","February","March","April","May","June","July","August","September","October","November","December"],"wgMonthNamesShort":["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"wgRelevantPageName":"Jurassic_Park","wgRelevantArticleId":11056991,"wgRequestId":"WVbtZgpAAEEAABgRKW4AAAAM","wgIsProbablyEditable":true,"wgRelevantPageIsProbablyEditable":true,"wgRestrictionEdit":[],"wgRestrictionMove":["sysop"],"wgFlaggedRevsParams":{"tags":{}},"wgStableRevisionId":null,"wgWikiEditorEnabledModules":{"toolbar":true,"preview":false,"publish":false},"wgBetaFeaturesFeatures":[],"wgMediaViewerOnClick":true,"wgMediaViewerEnabledByDefault":false,"wgPopupsShouldSendModuleToUser":false,"wgPopupsConflictsWithNavPopupGadget":false,"wgVisualEditor":{"pageLanguageCode":"en","pageLanguageDir":"ltr","usePageImages":true,"usePageDescriptions":true},"wgPreferredVariant":"en","wgMFExpandAllSectionsUserOption":false,"wgMFDisplayWikibaseDescriptions":{"search":true,"nearby":true,"watchlist":true,"tagline":false},"wgRelatedArticles":null,"wgRelatedArticlesUseCirrusSearch":true,"wgRelatedArticlesOnlyUseCirrusSearch":false,"wgULSCurrentAutonym":"English","wgNoticeProject":"wikipedia","wgCentralNoticeCookiesToDelete":[],"wgCentralNoticeCategoriesUsingLegacy":["Fundraising","fundraising"],"wgCategoryTreePageCategoryOptions":"{"mode":0,"hideprefix":20,"showcount":true,"namespaces":false}","wgWikibaseItemId":"Q2336369","wgCentralAuthMobileDomain":false,"wgVisualEditorToolbarScrollOffset":0,"wgVisualEditorUnsupportedEditParams":["preload","preloadparams","preloadtitle","undo","undoafter","veswitched"],"wgEditSubmitButtonLabelPublish":false});mw.loader.state({"ext.globalCssJs.user.styles":"ready","ext.globalCssJs.site.styles":"ready","site.styles":"ready","noscript":"ready","user.styles":"ready","user":"ready","user.options":"loading","user.tokens":"loading","ext.cite.styles":"ready","wikibase.client.init":"ready","ext.visualEditor.desktopArticleTarget.noscript":"ready","ext.uls.interlanguage":"ready","ext.wikimediaBadges":"ready","mediawiki.legacy.shared":"ready","mediawiki.legacy.commonPrint":"ready","mediawiki.sectionAnchor":"ready","mediawiki.skinning.interface":"ready","skins.vector.styles":"ready","ext.globalCssJs.user":"ready","ext.globalCssJs.site":"ready"});mw.loader.implement("user.options@0gii3s4",function($,jQuery,require,module){mw.user.options.set([]);});mw.loader.implement("user.tokens@1dqfd7l",function ( $, jQuery, require, module ) { mw.user.tokens.set({"editToken":"+\","patrolToken":"+
10、post提交json
Gson是一个在JSON和Java对象之间转换非常方便的api。这里我们用Gson来解析Github API的JSON响应。
注意:ResponseBody.charStream()
使用响应头Content-Type
指定的字符集来解析响应体。默认是UTF-8。
private void postJson() { new Thread() { @Override public void run() { Request request = new Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gson.fromJson(response.body().charStream(), Gist.class); for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) { Log.d(TAG, "key===>" + entry.getKey()); Log.d(TAG, "content===>" + entry.getValue().content); } } catch (IOException e) { e.printStackTrace(); } } }.start(); }
打印结果:
07-04 13:58:33.153 10928-11216/com.example.okhttpdemo D/MainActivity: key===>OkHttp.txt 07-04 13:58:33.153 10928-11216/com.example.okhttpdemo D/MainActivity: content===> \ // \ .ooo. // .@@@@@@@@@. :@@@@@@@@@@@@@: :@@. '@@@@@' .@@: @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ :@@ :@@@@@@@@@@@@@@@@@. @@: @@@ '@@@@@@@@@@@@@@@@@, @@@ @@@ '@@@@@@@@@@@@@@@@@, @@@ @@@ '@@@@@@@@@@@@@@@@@, @@@ @@@ '@@@@@@@@@@@@@@@@@, @@@ @@@ '@@@@@@@@@@@@@@@@@, @@@ @@@ '@@@@@@@@@@@@@@@@@, @@@ @@@@@@@@@@@@@@@@@ '@@@@@@@@@@@@@@@' @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ '@@' '@@' :@@@. .@@@@@@@: +@@ `@@ @@` @@ @@ .@@@@'@@@@: +@@ `@@ @@` @@ @@ @@@ @@@ +@@ `@@ @@` @@ @@ .@@ @@: +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@;@@@@@ @@@ @@@ +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@@@@@@@@ @@@ @@@ +@@ @@@ `@@@@@@@@@@` @@ @@ @@@ :@@ @@@ @@@ +@@@@@ `@@@@@@@@@@` @@ @@ @@# @@+ @@@ @@@ +@@@@@+ `@@ @@` @@ @@ @@: @@# @@: .@@` +@@@+@@ `@@ @@` @@ @@ @@# @@+ @@@. .@@@ +@@ @@@ `@@ @@` @@ @@ @@@ ,@@ @@@@@@@@@ +@@ @@@ `@@ @@` @@@@ @@@@ @@@@#@@@@ @@@@@@@ +@@ #@@ `@@ @@` @@@@: @@@@: @@'@@@@@ @@: @@: @@:
代码下载地址:http://download.csdn.net/detail/yihuangol/9888975
最后
以上就是谦让糖豆为你收集整理的okhttp3使用详解的全部内容,希望文章能够帮你解决okhttp3使用详解所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复