最近研究 Okhttp3, 把項目 down 下來后核无,發(fā)現(xiàn)不能編譯,真實尷尬藕坯。平時使用的都是 gradle, 但是該項目使用 maven团南,導(dǎo)入 idea 后已慢,摸索兩下霹购,用界面的命令行搞起朋腋。
image.png
項目中有好多 model, 本次主要看看 Okhttp3 的 get/post 請求旭咽。其實我們自己很容易就能寫出來,不過還是看看 官方 demo 的寫法吧轿塔。
get 請求
public class GetExample {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
這個里面需要提到的是 try(需要一次捕獲的代碼){正常后處理的代碼} 這是 java 7.0 以上的 try catch 結(jié)構(gòu)仲墨,操作方便勾缭。
post 請求
public class PostExample {
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();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
String bowlingJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1367702411696,"
+ "'dateStarted':1367702378785,"
+ "'players':["
+ "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
+ "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
+ "]}";
}
public static void main(String[] args) throws IOException {
PostExample example = new PostExample();
String json = example.bowlingJson("Jesse", "Jake");
String response = example.post("http://www.roundsapp.com/post", json);
System.out.println(response);
}
}
重點在這里『RequestBody.create(JSON, json)』, 構(gòu)建 post 的 body 的時候癌蚁,直接傳入 mediaType 和 json 內(nèi)容即可構(gòu)建成功兜畸。
下面還有好多咬摇,可以直接在 github 上查看:
image.png
異步 get 請求煞躬,猜猜結(jié)果是什么?
public final class AsynchronousGet {
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
}
});
System.out.println(" 異步了么龄坪?");
}
public static void main(String... args) throws Exception {
new AsynchronousGet().run();
}
}
結(jié)果亮起來了:
image.png
需要用戶登錄后才能訪問接口
我們 嘗試直接訪問 http://publicobject.com/secrets/hellosecret.txt
, 會強制我們登錄健田,否則就沒有返回值佛纫。
登錄名: jesse
登陸密碼: password1
會看到 android 的密鑰哈
public final class Authenticate {
private final OkHttpClient client;
public Authenticate() {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override public Request authenticate(Route route, Response response) throws IOException {
if (response.request().header("Authorization") != null) {
return null; // Give up, we've already attempted to authenticate.
}
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
}
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/secrets/hellosecret.txt")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
public static void main(String... args) throws Exception {
new Authenticate().run();
}
}