Okhttp3 - RequestBody.create(contentType, content) Deprecated - java

I did not find any example of how to replace the deprecation method.
The examples on the okhttp3 main page are old.
This is one of them:
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
If someone could solve it, I would appreciate your help.
Update:
I'm using 'com.squareup.okhttp3:okhttp:4.0.1'

Java Solution:
Use create(String, MediaType) instead of create(MediaType, String) for example
Kotlin Solution:
Use the extension function content.toRequestBody(contentType);
for the File type file.asRequestBody(contentType)
Note:
I'm using kotlin, but my IDE just doesn't automatically import the class or method like import okhttp3.RequestBody.Companion.toRequestBody, so I import it manually...then use it as the example given by Saeed Younus and Pratyesh below
For more: The documentation
(In Android Studio or any Jetbrain's IDE, the solution to the deprecated methods or class can be found by just holding the Ctrl and clicking on the create(...) of RequestBody.create)

In com.squareup.okhttp3:okhttp:4.1.0
MediaType.get("application/json; charset=utf-8") no more available.
instead this we need to use "application/json; charset=utf-8".toMediaTypeOrNull().
For example how we need to create request body now since okhttp:4.1.0
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
val jsonObject = JSONObject()
jsonObject.put("name", "Ancd test")
jsonObject.put("city", "delhi")
jsonObject.put("age", "23")
val body = jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
To those wondering where the answers are coming from!
All the alternatives/solutions(as described by the answer) are documented in the corresponding deprecated code! Just manoeuvre to it (the deprecated code) using whichever means your IDE supports. For example, to see the alternative/solution to the deprecated code RequestBody.create(...,...) when using AndroidStudio or any Jetbrain's IDE, just long-press Ctrl and hover over the RequestBody.create(...,...) then click on it when it's hovered over successfully

You need to import these files manually may be this is a bug in android studio. It is not suggested but this is work for Okhttp 4.2.2
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
and use as
val file = File("path")
file.asRequestBody("image/jpeg".toMediaTypeOrNull())

It was deprecated since version 4.0.0 of okhttp3.
The documentation for that version says
#JvmStatic
#Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, content: String) = content.toRequestBody(contentType)
I haven't tried it but I believe that you should be good by doing the following:
package com.example;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Test {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
public static void main(String[] args) {
}
String post(String url, String json) throws IOException {
//RequestBody body = RequestBody.create(JSON, json);
RequestBody body = RequestBody.Companion.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
Update: I tried to compile the file shown above using the following dependency version and RequestBody.Companion.create(json, JSON) doesn't seem to be deprecated.
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>

Can u update like that
val apiRequest = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "edit_group")
val tokenRequest = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), token)
val fileReqBody = RequestBody.create(MediaType.parse("image/*"), file)
to
val apiRequest = "edit_group".toRequestBody("text/plain;charset=utf-8".toMediaType())
val tokenRequest = token.toRequestBody("text/plain;charset=utf-8".toMediaType())
val file = File(path)
val fileReqBody = file.asRequestBody("image/*".toMediaType())

Just change ResponseBody.create(MediaType.parse("text/json"), plainBody.trim())
to ResponseBody.create(plainBody.trim(),MediaType.parse("text/json"))

Just had a quick look at the documentation . It reads deprecated, however the alternative is provided in the doc.
json.toRequestBody(contentType) should do the trick for you.
Below is the documentation link:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/RequestBody.kt
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.Companion.create(json, JSON)
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}

ok according to okhttp 4 many thing updated as official docs
RequestBody.create() is upgraded to File.asRequestBody()

You Just Need To Flip Your Args.
#kotlin.jvm.JvmStatic #kotlin.Deprecated public final fun create(contentType: okhttp3.MediaType?, file: java.io.File): okhttp3.RequestBody { }
#kotlin.jvm.JvmStatic #kotlin.Deprecated #kotlin.jvm.JvmOverloads public final fun create(contentType: okhttp3.MediaType?, content: kotlin.ByteArray, offset: kotlin.Int , byteCount: kotlin.Int): okhttp3.RequestBody {}
#kotlin.jvm.JvmStatic #kotlin.Deprecated public final fun create(contentType: okhttp3.MediaType?, content: kotlin.String): okhttp3.RequestBody {}
#kotlin.jvm.JvmStatic #kotlin.Deprecated public final fun create(contentType: okhttp3.MediaType?, content: okio.ByteString): okhttp3.RequestBody { }

Related

Can not get response from 000webhost using Retrofit in Android Studio

I am new to Android, i have a file named "https://codyderunner.000webhostapp.com/Server/songbannner.php" which response JSON like: Json response from my file
I want to get those JSON in Android studio using Retrofit.
I have a DataService interface:
public interface DataService {
#GET("songbannner.php")
Call<List<Ads>> GetDataBanner();
}
Ads is a model class of the Data I want to Receive.
My APIService.java file code:
public class APIService {
private static String base_url = "https://codyderunner.000webhostapp.com/Server/";
public static DataService getService(){
return APIRetrofitClient.getClient(base_url).create(DataService.class);
};
}
My API.RetrofitClient code:
public class APIRetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String base_url){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(10000, TimeUnit.MILLISECONDS)
.writeTimeout(10000, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.protocols(Arrays.asList(Protocol.HTTP_1_1))
.build();
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder()
.baseUrl(base_url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit;
};
In my main class, i have a function to get data from that file:
private void GetData(){
DataService dataService = APIService.getService();
Call<List<Ads>> callback = dataService.GetDataBanner();
callback.enqueue(new Callback<List<Ads>>() {
#Override
public void onResponse(Call<List<Ads>> call, Response<List<Ads>> response) {
ArrayList<Ads> banner = (ArrayList<Ads>) response.body();
Log.d("AAAA", banner.get(0).getNameSong());
}
#Override
public void onFailure(Call<List<Ads>> call, Throwable t) {
}
});
}
Now, the thing is, i can not receive any response from the file, I think it may because of the authentication when I try to get the data which the file response. Its fine when I open the link with the browser, cause it remember my password, but when I try to read the JSON of the File from Android Studio, Its seem hopeless. I also try to read the link on Postman, its released "Unauthorized", so I think the point is how can I put my user-name and password in Retrofit so the file will response as it did in the browser.
Is there anyone meet the same problem? Help me, I tried Everything I know. Many thanks.
OK, finally, I find out that the website which I store my .php file require user name and password, just add it into the Okhttpclient.
First, I created a java class called BasicAuthInterceptor:
import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class BasicAuthInterceptor implements Interceptor {
private String credentials;
public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}
And add it with password and username into your OkhttpClient:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.build();
with your username and password which you use to login into the website. It took me 2 days finding out, hell ya.

Send JSON in request OkHttp

Friends!
I have a simple HTTP request:
void postRequest(String postUrl,String phone, String message) throws IOException {
OkHttpClient client = new OkHttpClient();
//RequestBody body = RequestBody.create(JSON, postBody);
RequestBody body = new FormBody.Builder()
.add("phone", phone)
.add("message", message)
.build();
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
//System.out.println(request);
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
How to properly implement sending a JSON object instead of simple parameters?
My attempts were unsuccessful, so I really need a hint.
The server that will accept JSON is running on AKKA-HTTP.
How do I send a request to this server correctly?
final case class Message(phone: String, message: String, service: String)
implicit val item = jsonFormat3(Message)
val queue: Queue[Message] = Queue()
val addMessage = post {
path("add_message"){
parameters("phone".as[String], "message".as[String], "service".as[String]){
(phone, message, service) => {
queue.enqueue(Message(phone, message, service))
complete("ok")
}
}
}
}
The easiest way to map and serialize your object in JSON format is to use the ObjectMapper class of jackson-databind library.
I personally use it to implement integration tests of RestControllers and it works very well. Here is the utility class I realized, you can take it and use it for your purposes:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JsonUtils {
public static String json(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
}
What you need to have is a POJO class which implements Serializable, and then pass the instance of your class to the json method and it will return the JSON format.
You can definitely use it for Android projects. I found many examples where you can add the dependency, but it depends whether you use Gradle or Maven.
Try that out!!!
How do you like this option?
I tried to implement it, but the send fails.
I'm missing an important detail. But I don't understand what it is.
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}

How to add interceptor to all API requests except one or two?

I know it's possible to add an interceptor to all requests through an OkHttpClient, but I would like to know if it's possible to add headers to all requests in Okhttp except for one request or two using the OkHttpClient.
For example, in my API all requests require a bearer token (Authorization: Bearer token-here header) except for the oauth/token (to get a token) and api/users (to register a user) routes. Is it possible to add an interceptor for all requests except the excluded ones using the OkHttpClient in one step or should I add the headers individually for each request?
I found the answer!
Basically I needed an interceptor as usual and I needed to check the URL there to know whether I should add the authorization header or not.
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Omar on 4/17/2017.
*/
public class NetInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.url().encodedPath().equalsIgnoreCase("/oauth/token")
|| (request.url().encodedPath().equalsIgnoreCase("/api/v1/users") && request.method().equalsIgnoreCase("post"))) {
return chain.proceed(request);
}
Request newRequest = request.newBuilder()
.addHeader("Authorization", "Bearer token-here")
.build();
Response response = chain.proceed(newRequest);
return response;
}
}
#Omar answer is Good :) but I found a more clean way to implement using custom annotation.
Add annotation
#Target(AnnotationTarget.FUNCTION)
#Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE
check if the annotation is true or false in an intercepter like this
val method = chain.request().tag(Invocation::class.java)!!.method()
if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
//when annotion is present
} else..
add an annotation in retrofit interface
#DECRYPTRESPONSE
#GET
Call<ItemsModel> getListing(#Url String url);
below is the complete code of my interceptor also don't forget to add intercepter in the Okhttpclient builder
#Target(AnnotationTarget.FUNCTION)
#Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE
class DecryptInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain
.run {
proceed(request())
}
.let { response ->
return#let if (response.isSuccessful) {
val body = response.body!!
val contentType = body.contentType()
val charset = contentType?.charset() ?: Charset.defaultCharset()
val buffer = body.source().apply { request(Long.MAX_VALUE) }.buffer()
val bodyContent = buffer.clone().readString(charset)
val method = chain.request().tag(Invocation::class.java)!!.method()
if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
response.newBuilder()
.body(ResponseBody.create(contentType, bodyContent.let(::decryptBody)))
.build()
}
else{
response.newBuilder()
.body(ResponseBody.create(contentType, bodyContent))
.build()
}
} else response
}
private fun decryptBody(content: String): String {
return content //your decryption code
}
}

React Native & okhttp on Android - Set User-Agent

I'm trying to set the User-Agent with React Native on Android. Did some research and it looks like I should use an okhttp Interceptor. An example that I've found explains how this should be done(Link) but then I am not sure on how to register the Interceptor.
So in order to set the User-Agent I am using this class:
public class CustomInterceptor implements Interceptor {
#Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.removeHeader("User-Agent")
.header("User-Agent", "Trevor")
.build();
return chain.proceed(requestWithUserAgent);
}
}
Then what's left is to register the above interceptor so where it should be done? Maybe in MainActivity.java?
OkHttpClient okHttp = new OkHttpClient();
okHttp.interceptors().add(new CustomInterceptor());
I am not getting any errors when building the app so I think that the CustomInterceptor should be fine - just need to make the app use it.
UPDATE:
I'm currently trying to register the interceptor in MainActivity but it won't pick it up:
public class MainActivity extends ReactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new CustomInterceptor());
};
};
None of the answers here worked for me for RN 0.63.2. I was able to get it working and in my research was able to find the (albeit very scarce) documentation for the support of this feature.
The only documentation I could find for this was this PR where someone added support for this feature (and broke the currently accepted answer). When I tried adding the interceptor as documented in the PR I got an exception related to CookieJar which I was able to find a solution to in this (unresolved 🙄) issue.
TLDR:
Add a Java class in the same folder as your MainApplication called UserAgentInterceptor.java and place this in it:
package YOUR.PACKAGE.NAME; // <-- REPLACE ME
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class UserAgentInterceptor implements Interceptor {
public UserAgentInterceptor() {}
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.removeHeader("User-Agent")
.addHeader("User-Agent", "YOUR USER AGENT") // <-- REPLACE ME
.build();
return chain.proceed(requestWithUserAgent);
}
}
Then create another Java class in the same folder named UserAgentClientFactory.java and place this in it:
package YOUR.PACKAGE.NAME; // <-- REPLACE ME
import com.facebook.react.modules.network.OkHttpClientFactory;
import com.facebook.react.modules.network.ReactCookieJarContainer;
import okhttp3.OkHttpClient;
public class UserAgentClientFactory implements OkHttpClientFactory {
public OkHttpClient createNewNetworkModuleClient() {
return new OkHttpClient.Builder()
.cookieJar(new ReactCookieJarContainer())
.addInterceptor(new UserAgentInterceptor())
.build();
}
}
Then in your MainApplication onCreate method register the factory like this:
...
import com.facebook.react.modules.network.OkHttpClientProvider;
...
#Override
public void onCreate() {
super.onCreate();
OkHttpClientProvider.setOkHttpClientFactory(new UserAgentClientFactory());
// Your other code stuffs
}
And that's it!
So I've finally figured it out. Here is the solution for overriding the User-Agent of okhttp3 with React Native.
Create a file called CustomInterceptor.java:
package com.trevor;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class CustomInterceptor implements Interceptor {
public CustomInterceptor() {}
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.removeHeader("User-Agent")
.addHeader("User-Agent", "Trevor")
.build();
return chain.proceed(requestWithUserAgent);
}
}
Then in MainActivity.java override the onCreate method:
...
import com.facebook.react.modules.network.OkHttpClientProvider;
...
public class MainActivity extends ReactActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
attachInterceptor();
}
private void attachInterceptor() {
OkHttpClient client = OkHttpClientProvider.getOkHttpClient();
client.networkInterceptors().add(new CustomInterceptor());
}
}
Note that I'm importing com.facebook.react.modules.network.OkHttpClientProvider; and overriding that client instead of creating a vanilla OkHttpClient since this is the one that React Native will use.
React Native is iterating so quickly that the accepted answer didn't work for me.
For RN 0.27.2 I had to import okhttp3.OkHttpClient in my CustomInterceptor and change the attachInterceptor() method in MainActivity to replace the client.
private void attachInterceptor() {
OkHttpClient currentClient = OkHttpClientProvider.getOkHttpClient();
OkHttpClient replacementClient = currentClient.newBuilder().addNetworkInterceptor(new CustomInterceptor()).build();
OkHttpClientProvider.replaceOkHttpClient(replacementClient);
}
Everything else from ekonstantinidis's answer works for me.
Old issue, but we still ran into the same problem with React Native 0.59. This is what we did to fix (in Kotlin), as recent versions of okhttp prevent (and throw an exception) when trying to add an interceptor to an already initialized client:
import android.os.Build
import com.facebook.react.modules.network.OkHttpClientFactory
import com.jaredrummler.android.device.DeviceName
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class UserAgentInterceptor(val userAgent: String): Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val correctRequest = originalRequest.newBuilder()
.removeHeader("User-Agent")
.addHeader("User-Agent", userAgent)
.build()
return chain.proceed(correctRequest)
}
}
class UserAgentClientFactory(val appName: String, val appVersion: String, val buildNumber: String): OkHttpClientFactory {
private fun userAgentValue(): String {
val deviceName = DeviceName.getDeviceName()
val osVersion = Build.VERSION.RELEASE
return "$appName/$appVersion (build: $buildNumber; device: $deviceName; OS: Android $osVersion)"
}
override fun createNewNetworkModuleClient(): OkHttpClient {
val builder = com.facebook.react.modules.network.OkHttpClientProvider.createClientBuilder()
return builder.addInterceptor(UserAgentInterceptor(userAgent = userAgentValue())).build()
}
}
This was done in a shared library between 2 apps, thus why we passed in the app name, version, and build number.
Usage from the app itself looked like:
private fun configureUserAgent() {
val versionName = BuildConfig.VERSION_NAME
val versionCode = BuildConfig.VERSION_CODE
OkHttpClientProvider.setOkHttpClientFactory(UserAgentClientFactory(appName = "My App", appVersion = versionName, buildNumber = "$versionCode"))
}
This was called from the onCreate method in the main activity of the app.
Hope this helps!
I've implemented this functionality using OkHttp and my code is pretty the same as yours - and everything works fine.
Consider using addHeader("User-Agent", "Trevor") instead of header("User-Agent", "Trevor"), because the latter will replace all of already set headers.
I'm using okHttp.networkInterceptors().add(new CustomInterceptor()); instead of okHttp.interceptors().add(new CustomInterceptor());, but I don't think it's a matter of concern here.
Update I do it in onCreate() method too. Everything works as it should.

How to add query parameters to a HTTP GET request by OkHttp?

I am using the latest okhttp version: okhttp-2.3.0.jar
How to add query parameters to GET request in okhttp in java ?
I found a related question about android, but no answer here!
For okhttp3:
private static final OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
public static void get(String url, Map<String,String>params, Callback responseCallback) {
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
if (params != null) {
for(Map.Entry<String, String> param : params.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(),param.getValue());
}
}
Request request = new Request.Builder().url(httpBuilder.build()).build();
client.newCall(request).enqueue(responseCallback);
}
Here's my interceptor
private static class AuthInterceptor implements Interceptor {
private String mApiKey;
public AuthInterceptor(String apiKey) {
mApiKey = apiKey;
}
#Override
public Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().url()
.newBuilder()
.addQueryParameter("api_key", mApiKey)
.build();
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
}
}
I finally did my code, hope the following code can help you guys. I build the URL first using
HttpUrl httpUrl = new HttpUrl.Builder()
Then pass the URL to Request requesthttp hope it helps .
public class NetActions {
OkHttpClient client = new OkHttpClient();
public String getStudentById(String code) throws IOException, NullPointerException {
HttpUrl httpUrl = new HttpUrl.Builder()
.scheme("https")
.host("subdomain.apiweb.com")
.addPathSegment("api")
.addPathSegment("v1")
.addPathSegment("students")
.addPathSegment(code) // <- 8873 code passthru parameter on method
.addQueryParameter("auth_token", "71x23768234hgjwqguygqew")
// Each addPathSegment separated add a / symbol to the final url
// finally my Full URL is:
// https://subdomain.apiweb.com/api/v1/students/8873?auth_token=71x23768234hgjwqguygqew
.build();
System.out.println(httpUrl.toString());
Request requesthttp = new Request.Builder()
.addHeader("accept", "application/json")
.url(httpUrl) // <- Finally put httpUrl in here
.build();
Response response = client.newCall(requesthttp).execute();
return response.body().string();
}
}
As mentioned in the other answer, okhttp v2.4 offers new functionality that does make this possible.
See http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/HttpUrl.Builder.html#addQueryParameter-java.lang.String-java.lang.String-
This is not possible with the current version of okhttp, there is no method provided that will handle this for you.
The next best thing is building an url string or an URL object (found in java.net.URL) with the query included yourself, and pass that to the request builder of okhttp.
As you can see, the Request.Builder can take either a String or an URL.
Examples on how to build an url can be found at What is the idiomatic way to compose a URL or URI in Java?
As of right now (okhttp 2.4), HttpUrl.Builder now has methods addQueryParameter and addEncodedQueryParameter.
You can create a newBuilder from existing HttoUrl and add query parameters there. Sample interceptor code:
Request req = it.request()
return chain.proceed(
req.newBuilder()
.url(
req.url().newBuilder()
.addQueryParameter("v", "5.60")
.build());
.build());
Use HttpUrl class's functions:
//adds the pre-encoded query parameter to this URL's query string
addEncodedQueryParameter(String encodedName, String encodedValue)
//encodes the query parameter using UTF-8 and adds it to this URL's query string
addQueryParameter(String name, String value)
more detailed: https://stackoverflow.com/a/32146909/5247331

Categories

Resources