简单的get和post请求
依赖
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.2'
implementation 'net.qiujuer.common:okhttp:3.0.0'
get请求
public final static int CONNECT_TIMEOUT = 60;
public final static int READ_TIMEOUT = 100;
public final static int WRITE_TIMEOUT = 60;
public static final OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.build();
public String get(String url) throws IOException{
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
String res = response.body().string();
return res;
}else{
throw new IOException("Unexpected code " + response);
}
}
post请求(带参数)
public static String post1(String url,String json) throws IOException {
RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
Log.i("json:",json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String res = response.body().string();
Log.i("返回结果:", res);
return res;
} else {
throw new IOException("Unexpected code " + response);
}
}
post带token请求
public String post(String url, String json) throws IOException {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON,json);
Log.i("token值",token);
Request request = new Request.Builder()
.url(url)
.addHeader("authorization",token)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String res = response.body().string();
Log.i("返回结果:", res);
return res;
} else {
throw new IOException("Unexpected code " + response);
}
}