I have a method that I use it for sending all my requests to the Server. And in this method I'm using of Builder class. I just want to know how can I specify the type of Builder's function by "if" in each request according to the inputs of the function. here is my function:
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 "";
}
So what should I do?!
You can use builders either by chaining or separately.
You can try something like this:
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();