我有一个方法可以将我所有的请求发送到服务器。 在这个方法中,我使用了 Builder 类。 我只想知道如何根据函数的输入在每个请求中通过“if”指定Builder函数的类型。 这是我的功能:
public String sendHttpRequest(String url, String parameters,String type) {
try {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, parameters);
Request request = new Request.Builder()
.url(url)
/*what I'm going to do is somthing like this:
if(type.equal("get")){
.get()
}
if(type.equal("post")){
.post()
}
*/
.addHeader("content-type", "application/json")
.addHeader("cache-control", "no-cache")
Response response = client.newCall(request).execute();
return response.body().string().toString();
} catch (IOException ex) {
}
return "";
}
那我该怎么办?!
最佳答案
您可以通过链接或单独使用构建器。
你可以尝试这样的事情:
Request.Builder builder = new Request.Builder()
.url(url)
.addHeader("content-type", "application/json")
.addHeader("cache-control", "no-cache");
if(type.equals("get")){
builder.get();
} else if(type.equals("post")){
builder.post(/*body*/);
}
Request request = builder.build();
Response response = client.newCall(request).execute();
关于java - 如何选择要在 Builder 类中使用的函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586192/