OkHttp工具类
2019-10-01 本文已影响0人
凌康ACG
import java.io.IOException;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* okhttp 网络请求
*/
public class OkHttp {
private OkHttpClient client = new OkHttpClient();
/**
* Get 请求
*
* @return String
*/
String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
/**
* Post 请求
*
* @return String
*/
String post(String url, Map<String, String> param) throws IOException {
FormBody.Builder body = new FormBody.Builder();
for (String key : param.keySet()) {
body.add(key, param.get(key)).build();
}
RequestBody requestBody = body.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}