Sending different format json to Okhttp [duplicate] - android

This question already has answers here:
Sending JSON body through POST request in OKhttp in Android
(2 answers)
Closed 4 years ago.
for normal json like
{
"text1":"going",
"text2":"sending"
}
i'm using okhttp3 as
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("text1",xxx)
.addFormDataPart("text2","yyy")
.build();
how do i use it to send for jsons like
{"Text1":"aaa","text2":[{"module":"bbb","Text":"xxx","params":{"lang": "eng"}}]}

Try this
Add Gradle depends compile 'com.squareup.okhttp3:okhttp:3.2.0'
public static JSONObject foo(String url, JSONObject json) {
JSONObject jsonObjectResp = null;
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
okhttp3.RequestBody body = RequestBody.create(JSON, json.toString());
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(body)
.build();
okhttp3.Response response = client.newCall(request).execute();
String networkResp = response.body().string();
if (!networkResp.isEmpty()) {
jsonObjectResp = parseJSONStringToJSONObject(networkResp);
}
} catch (Exception ex) {
String err = String.format("{\"result\":\"false\",\"error\":\"%s\"}", ex.getMessage());
jsonObjectResp = parseJSONStringToJSONObject(err);
}
return jsonObjectResp;
}

Related

OKHTTP how to pass JSON to FormBody [duplicate]

So, back when I was using Koush's Ion, I was able to add a json body to my posts with a simple .setJsonObjectBody(json).asJsonObject()
I'm moving over to OkHttp, and I really don't see a good way to do that. I'm getting error 400's all over the place.
Anyone have any ideas?
I've even tried manually formatting it as a json string.
String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);
String url = mBaseUrl + "/" + id + "/report";
Request request = new Request.Builder()
.header("X-Client-Type", "Android")
.url(url)
.post(RequestBody
.create(MediaType
.parse("application/json"),
"{\"Reason\": \"" + reason + "\"}"
))
.build();
client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException(
"Unexpected code " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});
}
});
/*Ion.with(getContext(), url)
.setHeader("X-Client-Type", "Android")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});*/
Just use JSONObject.toString(); method.
And have a look at OkHttp's tutorial:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON); // new
// RequestBody body = RequestBody.create(JSON, json); // old
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
You can create your own JSONObject then toString().
Remember run it in the background thread like doInBackground in AsyncTask.
OkHttp version > 4:
import okhttp3.MediaType.Companion.toMediaType
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// 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();
}
Another approach is by using FormBody.Builder().
Here's an example of callback:
Callback loginCallback = new Callback() {
#Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// String loginResponseString = response.body().string();
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i(TAG, "loginResponseString: " + loginResponseString);
}
};
Then, we create our own body:
RequestBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", password)
.add("customCredential", "")
.add("isPersistent", "true")
.add("setCookie", "true")
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(this)
.build();
Request request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
Finally, we call the server:
client.newCall(request).enqueue(loginCallback);
In kotlin, in okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc

Glide POST request for image

I'm trying to download image from server with POST (json body). To accomplish that I created okhttp interceptor:
private static class PostThumbnailRequestInterceptor implements Interceptor {
private static final String DEVICE_GUID = "device_guid";
private static final String RESOURCE_GUIDS = "resource_guids";
private static final String UTC_TIMESTAMP = "utc_timestamp";
private String mChannelGuid;
private String mResourceGuid;
public PostThumbnailRequestInterceptor(String channelGuid, String resourceGuid) {
mChannelGuid = channelGuid;
mResourceGuid = resourceGuid;
}
#Override
public Response intercept(Chain chain) throws IOException {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
JSONArray resources = new JSONArray();
resources.put(mResourceGuid);
JSONObject requestedThumbnail = new JSONObject();
JSONObject payload = new JSONObject();
try {
requestedThumbnail.put(UTC_TIMESTAMP, System.currentTimeMillis() * 1000);
requestedThumbnail.put(DEVICE_GUID, mChannelGuid);
requestedThumbnail.put(RESOURCE_GUIDS, resources);
payload.put("thumbnails", new JSONArray() {{put(requestedThumbnail);}});
} catch (JSONException e) {
throw new IOException("Failed to create payload");
}
RequestBody body = RequestBody.create(JSON, payload.toString());
final Request original = chain.request();
final Request.Builder requestBuilder = original.newBuilder()
.url(original.url())
.post(body);
//return chain.proceed(requestBuilder.build());
Response response = chain.proceed(requestBuilder.build());
try {
MediaType contentType = MediaType.parse("data:image/jpeg;base64");// response.body().contentType();
JSONObject object = new JSONObject(response.body().string());
String base64String = object.optJSONArray("thumbnails").getJSONObject(0).optString("content");
base64String = base64String.replace("data:image/jpeg;base64,", "");
byte[] rawImage = Base64.decode(base64String , Base64.DEFAULT);
ResponseBody realResponseBody = ResponseBody.create(contentType, rawImage);
response = response.newBuilder().body(realResponseBody).build();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
}
And using it like this
OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(new PostThumbnailRequestInterceptor(channel.id.getServerId(), channel.id.getChannelId()))
.build();
GlideApp.get(getContext())
.getRegistry().replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(mOkHttpClient));
It is works well with 1 request per time, but if I bind it with recycler view, replacing classes in Glide with dynamic interceptor produce a lot of errors (failed to load resource).
Am I on right way to request post or it is only 1 way - firstly request as usual and then pass decoded bytes to Glide?

How do I post data using okhttp library with content type x-www-form-urlencoded?

I have used this method https://stackoverflow.com/a/31744565/5829906 but doesnt post data.
Here is my code
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome")
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
response.body().close();
}catch (Exception e) {
e.printStackTrace();
}
I tried DefaultHttpClient , that seems to be working, but it shows deprecated, so thought of trying something different..Cant figure out what is wrong in this
You select MediaType MultipartBuilder.FORM
which is for uploading the file/image as multipart
public static final MediaType FORM = MediaType.parse("multipart/form-data");
try to send like this as
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build();
Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
For those that may still come here, using with Retrofi2 and passing your data correctly to the request body. Even if you set "application/x-www-form-urlencoded" and you did not pass your data properly, you will still have issue. That was my situstion
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("ContentType", "application/x-www-form-urlencoded");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api api = retrofit.create(Api.class);
Then make sure you pass your data to your api endpoint as shown below. NOT as JSON, or class object or string but as request body.
RequestBody formBody = new FormBody.Builder()
.addEncoded("grant_type", "password")
.addEncoded("username", username)
.addEncoded("password", password)
.build();
call your api service
Call<Response> call = api.login(formBody);
I hope this helps somebody

Retrofit2: Modifying request body in OkHttp Interceptor

I am using Retrofit 2 (2.0.0-beta3) with OkHttp client in Android application and so far everything going great. But currently I am facing issue with OkHttp Interceptor. The server I am communicating with is taking access token in body of request, so when I intercept the request to add auth token or in authenticate method of Authenticator when I need to add updated auth token, I need to modify body of request for this purpose. But it looks like I can only add data in headers but not in the body of ongoing request. The code I have written so far is as follows:
client.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (UserPreferences.ACCESS_TOKEN != null) {
// need to add this access token in request body as encoded form field instead of header
request = request.newBuilder()
.header("access_token", UserPreferences.ACCESS_TOKEN))
.method(request.method(), request.body())
.build();
}
Response response = chain.proceed(request);
return response;
}
});
Can anyone point me to the right direction as how to modify request body to add my access token (first time or updated after token refresh)? Any pointer to right direction would be appreciated.
I using this to add post parameter to the existing ones.
OkHttpClient client = new OkHttpClient.Builder()
.protocols(protocols)
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
RequestBody formBody = new FormEncodingBuilder()
.add("email", "Jurassic#Park.com")
.add("tel", "90301171XX")
.build();
String postBodyString = Utils.bodyToString(request.body());
postBodyString += ((postBodyString.length() > 0) ? "&" : "") + Utils.bodyToString(formBody);
request = requestBuilder
.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString))
.build();
return chain.proceed(request);
}
})
.build();
public static String bodyToString(final RequestBody request){
try {
final RequestBody copy = request;
final Buffer buffer = new Buffer();
if(copy != null)
copy.writeTo(buffer);
else
return "";
return buffer.readUtf8();
}
catch (final IOException e) {
return "did not work";
}
}
OkHttp3:
RequestBody formBody = new FormBody.Builder()
.add("email", "Jurassic#Park.com")
.add("tel", "90301171XX")
.build();
I'll share my Kotlin implementation of #Fabian's answer using Dagger. I wanted origin=app added to the request url for GET requests, and added to the body for form-encoded POST requests
#Provides
#Singleton
fun providesRequestInterceptor() =
Interceptor {
val request = it.request()
it.proceed(when (request.method()) {
"GET" -> {
val url = request.url()
request.newBuilder()
.url(url.newBuilder()
.addQueryParameter("origin", "app")
.build())
.build()
}
"POST" -> {
val body = request.body()
request.newBuilder()
.post(RequestBody.create(body?.contentType(),
body.bodyToString() + "&origin=app"))
.build()
}
else -> request
})
}
fun RequestBody?.bodyToString(): String {
if (this == null) return ""
val buffer = okio.Buffer()
writeTo(buffer)
return buffer.readUtf8()
}
Since this cannot be written in the comments of the previous answer by #Fabian, I am posting this one as separate answer. This answer deals with both "application/json" as well as form data.
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
/**
* Created by debanjan on 16/4/17.
*/
public class TokenInterceptor implements Interceptor {
private Context context; //This is here because I needed it for some other cause
//private static final String TOKEN_IDENTIFIER = "token_id";
public TokenInterceptor(Context context) {
this.context = context;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
String token = "toku";//whatever or however you get it.
String subtype = requestBody.contentType().subtype();
if(subtype.contains("json")){
requestBody = processApplicationJsonRequestBody(requestBody, token);
}
else if(subtype.contains("form")){
requestBody = processFormDataRequestBody(requestBody, token);
}
if(requestBody != null) {
Request.Builder requestBuilder = request.newBuilder();
request = requestBuilder
.post(requestBody)
.build();
}
return chain.proceed(request);
}
private String bodyToString(final RequestBody request){
try {
final RequestBody copy = request;
final Buffer buffer = new Buffer();
if(copy != null)
copy.writeTo(buffer);
else
return "";
return buffer.readUtf8();
}
catch (final IOException e) {
return "did not work";
}
}
private RequestBody processApplicationJsonRequestBody(RequestBody requestBody,String token){
String customReq = bodyToString(requestBody);
try {
JSONObject obj = new JSONObject(customReq);
obj.put("token", token);
return RequestBody.create(requestBody.contentType(), obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private RequestBody processFormDataRequestBody(RequestBody requestBody, String token){
RequestBody formBody = new FormBody.Builder()
.add("token", token)
.build();
String postBodyString = bodyToString(requestBody);
postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
return RequestBody.create(requestBody.contentType(), postBodyString);
}
}
You can edit the request body by below method, Pass the request and the parameter to edit.
private fun editBody(request: Request, parameter: String): RequestBody {
val oldBody = request.body //retrieve the current request body
val buffer = Buffer()
oldBody?.writeTo(buffer)
val strOldBody = buffer.readUtf8() // String representation of the current request body
buffer.clear()
buffer.close()
val strNewBody = JSONObject(strOldBody).put("parameter", parameter).toString()
return strNewBody.toRequestBody(request.body?.contentType()) // New request body with the encrypted/modified string of the current request body
}
Now you can request again with updated request body
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
return chain.proceed(requestWithUpdatedParameter(request, "parameter"))
}
private fun requestWithUpdatedParameter(req: Request, parameter: String): Request {
val newRequest: Request
val body = editBody(req, parameter)
newRequest = req.newBuilder().method(req.method, body).build()
return newRequest
}
private static class NetworkInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody oldBody = request.body(); //retrieve the current request body
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8(); // String representation of the current request body
buffer.clear();
buffer.close();
MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
String strNewBody = enDecService.encryptBody(strOldBody); // Your encryption/ modification logic
RequestBody body = RequestBody.create(mediaType, strNewBody); // New request body with the encrypted/modified string of the current request body
request = request.newBuilder()
.header("Content-Type", "application/json")
.header("Content-Length", String.valueOf(body.contentLength()))
.header("Authorization", "Bearer " + "your token")
.method(request.method(), body).build();
long t1 = System.nanoTime();
Log.d(TAG, String.format("Sending request %s on %s", request.url(), request.headers()));
Response response = chain.proceed(request); // sending req. to server. current req. body is a encrypted string.
int maxAge = 6000; // read from cache for 6000 seconds even if there is internet connection
response.header("Cache-Control", "public, max-age=" + maxAge);
response = response.newBuilder().removeHeader("Pragma").build();
long t2 = System.nanoTime();
Log.d(TAG, String.format("Received response for %s in %.1fms %s", response.request().url(), (t2 - t1) / 1e6d, response.toString()));
try {
String s = response.body().string(); // retrieve string representation of encrypted response assuming your response is encrypted.
ResponseBody responseBody = ResponseBody.create(mediaType, enDecService.decryptBody(s)); // decrypt the encrypted response or make other modifications.yor decryption/modifications logic goes here.
response = response.newBuilder().body(responseBody).build(); // build a new response with the decrypted response body.
} catch (JOSEException e) {
} catch (ParseException e) {
}
return response;
}
}
I'm using this way to verify my token
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS) //retrofit default 10 seconds
.writeTimeout(30, TimeUnit.SECONDS) //retrofit default 10 seconds
.readTimeout(30, TimeUnit.SECONDS) //retrofit default 10 seconds
.addInterceptor(logging.setLevel(HttpLoggingInterceptor.Level.BODY))
.addInterceptor(new BasicAuthInterceptor())
.build();
Here i'm sending token through BasicAuthInterceptor
public class MyServiceInterceptor implements Interceptor {
private String HEADER_NAME="Authorization";
private String OBJECT_NAME="Bearer";
private String SPACE=" ";
#Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
String token= PreferenceManager.getInstance().getString(PreferenceManager.TOKEN);
if (token != null) { {
requestBuilder.addHeader(HEADER_NAME, OBJECT_NAME+SPACE+ token);
}
}
return chain.proceed(requestBuilder.build());
}
}

OkHttp Post Body as JSON

So, back when I was using Koush's Ion, I was able to add a json body to my posts with a simple .setJsonObjectBody(json).asJsonObject()
I'm moving over to OkHttp, and I really don't see a good way to do that. I'm getting error 400's all over the place.
Anyone have any ideas?
I've even tried manually formatting it as a json string.
String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);
String url = mBaseUrl + "/" + id + "/report";
Request request = new Request.Builder()
.header("X-Client-Type", "Android")
.url(url)
.post(RequestBody
.create(MediaType
.parse("application/json"),
"{\"Reason\": \"" + reason + "\"}"
))
.build();
client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException(
"Unexpected code " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});
}
});
/*Ion.with(getContext(), url)
.setHeader("X-Client-Type", "Android")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});*/
Just use JSONObject.toString(); method.
And have a look at OkHttp's tutorial:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON); // new
// RequestBody body = RequestBody.create(JSON, json); // old
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
You can create your own JSONObject then toString().
Remember run it in the background thread like doInBackground in AsyncTask.
OkHttp version > 4:
import okhttp3.MediaType.Companion.toMediaType
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// 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();
}
Another approach is by using FormBody.Builder().
Here's an example of callback:
Callback loginCallback = new Callback() {
#Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// String loginResponseString = response.body().string();
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i(TAG, "loginResponseString: " + loginResponseString);
}
};
Then, we create our own body:
RequestBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", password)
.add("customCredential", "")
.add("isPersistent", "true")
.add("setCookie", "true")
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(this)
.build();
Request request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
Finally, we call the server:
client.newCall(request).enqueue(loginCallback);
In kotlin, in okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc

Categories

Resources