okhttp,get,post,put,delete 請求
public static String doGet(String url){
//创建一个Request
final Request request = new Request.Builder()
.url(url)
.build();
return execute(request);
}
public static String doPost(String url,String reqbody,Map<String,Object> map){
FormEncodingBuilder builder=addParamToBuilder(reqbody, map);
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return execute(request);
}
public static String doPut(String url,String reqbody,Map<String,Object> map){
FormEncodingBuilder builder=addParamToBuilder(reqbody, map);
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.put(body)
.build();
return execute(request);
}
public static String doDelete(String url,String reqbody,Map<String,Object> map){
FormEncodingBuilder builder=addParamToBuilder(reqbody, map);
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.delete(body)
.build();
return execute(request);
}
public static FormEncodingBuilder addParamToBuilder(String reqbody,Map<String,Object> map){
FormEncodingBuilder builder=new FormEncodingBuilder();
if(!StringUtils.isEmpty(reqbody)){
if(reqbody.startsWith("?")){
reqbody=reqbody.substring(1);
}
String[] params=reqbody.split("&");
for(int i=0;i<params.length;i++){
if(params[i].equals("")){
continue;
}
String [] kv=params[i].split("=");
builder.add(kv[0], kv[1]);
}
}
if(map!=null){
Iterator<Entry<String,Object>> ite= map.entrySet().iterator();
for(;ite.hasNext();){
Entry<String,Object> kv=ite.next();
builder.add(kv.getKey(), kv.getValue().toString());
}
}
return builder;
}
public static String execute(Request request){
try {
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return "{\"error\":\"fail\"}";
}