创建工程
1,在AS中创建普通android工程
2,创建一个module
选择Java or Kotlin Library
3,引入okhttp库
我这边module取名为“okhttpTest”,找到modulel下的build.gradle,加入依赖:
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
插入依赖
请到https://github.com/square/okhttp查看最新的版本号:
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”就可以执行了。如果有问题,可以手动配置:
打开运行配置界面 运行配置
配置后,就可以执行“Run”了,检查打印是否正常:
检查运行后打印是否正常
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源码了。
网友评论