GET请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://...")
.get()
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.d(TAG, "run: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
POST请求
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("...",...)
...
.build();
Request request = new Request.Builder()
.url("http://...")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.d(TAG, "run: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
解析POST获取的JSON数据
JSONObject jsonObject = null;
int status = 0;
try {
jsonObject = new JSONObject(retString);
status = jsonObject.getInt("status");
} catch (JSONException e) {
e.printStackTrace();
}
带cookies的请求
private static HashMap<String, List> cookieStore = new HashMap<>();
public static OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(60000, TimeUnit.MILLISECONDS)
.readTimeout(60000, TimeUnit.MILLISECONDS)
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List cookies = cookieStore.get(url.host());
return cookies!=null ? cookies : new ArrayList();
}
})
.build();