Android - HTTP util class SyncGET & SyncPOST
- gradle module 文件添加:
compile 'com.squareup.okhttp3:okhttp:3.9.1'
- 实现工具类
public class UtilHttp {
private static final String TAG = "UtilHttp";
public static String err;
public static String okPostUrlEncoded(String url,RequestBody body) {
try{
final MediaType URLENCODED
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
String ret = response.body().string();
return ret;
}
catch (IOException ex){
Log.v("UtilHTTP->IOException",ex.getMessage());
return "";
}
catch (Exception ex){
Log.v("UtilHTTP-Exception",ex.getMessage());
return "";
}
}
public static String okPostJson(String url,String json) {
try{
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
String ret = response.body().string();
return ret;
}
catch (IOException ex){
Log.v("UtilHTTP->IOException",ex.getMessage());
return "";
}
}
public static String okGet(String url){
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
String ret = response.body().string();
return ret;
}
catch (IOException ex){
Log.v("UtilHTTP->IOException",ex.getMessage());
return "";
}
}
}