手把手用Android stdio写OKHTTP java工程d
2020-03-28 本文已影响0人
浪里_个郎
创建工程
1,在AS中创建普通android工程
2,创建一个module
![](https://img.haomeiwen.com/i12785397/0e720e30059fbc59.png)
![](https://img.haomeiwen.com/i12785397/60847f5f4537fa0a.png)
3,引入okhttp库
我这边module取名为“okhttpTest”,找到modulel下的build.gradle,加入依赖:
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
![](https://img.haomeiwen.com/i12785397/d5f1ababed92ef90.png)
请到https://github.com/square/okhttp查看最新的版本号:
![](https://img.haomeiwen.com/i12785397/a15977c48c6cc4ed.png)
4,module运行配置
我们先加入main函数:
package com.example.okhttptest;
import java.io.IOException;
public class OKHttpTest {
public static void main(String[] args) throws IOException {
System.out.println("hello");
}
}
正常情况下,直接执行“Run”就可以执行了。如果有问题,可以手动配置:
![](https://img.haomeiwen.com/i12785397/4eb8ec7218b4378e.png)
![](https://img.haomeiwen.com/i12785397/d13c77e8293292f9.png)
配置后,就可以执行“Run”了,检查打印是否正常:
![](https://img.haomeiwen.com/i12785397/cea9402a9efaa232.png)
OK,目前工程已经正常创建。
编写OKHTTP测试代码
Get / Post测试
package com.example.okhttptest;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OKHttpTest {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
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();
}
}
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 {
OKHttpTest example = new OKHttpTest();
String responseGet = example.run("https://github.com/square/okhttp/blob/master/README.md");
System.out.println(responseGet);
String json = example.bowlingJson("Jesse", "Jake");
String responsePost = example.post("http://www.roundsapp.com/post", json);
System.out.println(responsePost);
}
}
运行一下,我们就可以通过Get / Post获得返回的HTTP源码了。