Image upload using okHttp - android

i want to upload image using okhttp but i am not able to find MultipartBuilder for Post Image.What can i use instead of this.
Here is my code
public static JSONObject uploadImage(File file) {
try {
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody req = new MultipartBuilder().setType(MultipartBody.FORM)
.addFormDataPart("userid", "8457851245")
.addFormDataPart(
"userfile",
"profile.png",
RequestBody.create(MEDIA_TYPE_PNG, file)
)
.build();
Request request = new Request.Builder()
.url("url")
.post(req)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
Log.d("response", "uploadImage:" + response.body().string());
return new JSONObject(response.body().string());
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
}
return null;
}
Thanks in advance.

You need to Use
new MultipartBody.Builder()
Instead of
new MultipartBuilder()
Its working

Here is the multi part request class.
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpStatus;
import android.content.Context;
import com.esp.ro.util.Config;
import com.esp.ro.util.Log;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
public class MultipartRequest {
public Context caller;
public MultipartBuilder builder;
private OkHttpClient client;
public MultipartRequest(Context caller) {
this.caller = caller;
this.builder = new MultipartBuilder();
this.builder.type(MultipartBuilder.FORM);
this.client = new OkHttpClient();
}
public void addString(String name, String value) {
this.builder.addFormDataPart(name, value);
}
public void addFile(String name, String filePath, String fileName) {
this.builder.addFormDataPart(name, fileName, RequestBody.create(
MediaType.parse("image/jpeg"), new File(filePath)));
}
public void addTXTFile(String name, String filePath, String fileName) {
this.builder.addFormDataPart(name, fileName, RequestBody.create(
MediaType.parse("text/plain"), new File(filePath)));
}
public void addZipFile(String name, String filePath, String fileName)
{
this.builder.addFormDataPart(name, fileName, RequestBody.create(
MediaType.parse("application/zip"), new File(filePath)));
}
public String execute(String url) {
RequestBody requestBody = null;
Request request = null;
Response response = null;
int code = 200;
String strResponse = null;
try {
requestBody = this.builder.build();
request = new Request.Builder().header("AUTH-KEY", Config.API_KEY)
.url(url).post(requestBody).build();
Log.print("::::::: REQ :: " + request);
response = client.newCall(request).execute();
Log.print("::::::: response :: " + response);
if (!response.isSuccessful())
throw new IOException();
code = response.networkResponse().code();
if (response.isSuccessful()) {
strResponse = response.body().string();
} else if (code == HttpStatus.SC_NOT_FOUND) {
// ** "Invalid URL or Server not available, please try again" */
strResponse = caller.getResources().getString(
R.string.error_invalid_URL);
} else if (code == HttpStatus.SC_REQUEST_TIMEOUT) {
// * "Connection timeout, please try again", */
strResponse = caller.getResources().getString(
R.string.error_timeout);
} else if (code == HttpStatus.SC_SERVICE_UNAVAILABLE) {
// *
// "Invalid URL or Server is not responding, please try again",
// */
strResponse = caller.getResources().getString(
R.string.error_server_not_responding);
}
} catch (Exception e) {
Log.error("Exception", e);
Log.print(e);
} finally {
requestBody = null;
request = null;
response = null;
builder = null;
if (client != null)
client = null;
System.gc();
}
return strResponse;
}
}
Hope this help you.
Note : If you are using old OkHttp which is below version 3 then you can use this method.If you are using version 3 or above here is the answer for you.

I used this way in OKHTTP 3.4.1
Call function like this
if (!realPath.equals("")) {
new SignupWithImageTask().execute(et_name.getText().toString(), et_email.getText().toString(), et_dob.getText().toString(), IMEI, et_mobile.getText().toString(), realPath);
} else {
Toast.makeText(this, "Profile Picture not found", Toast.LENGTH_SHORT).show();
}
SignupWithImageTask
public class SignupWithImageTask extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(SignupActivity.this);
progressDialog.setMessage("Please Wait....");
progressDialog.show();
}
#Override
protected String doInBackground(String... str) {
String res = null;
try {
// String ImagePath = str[0];
String name = str[0], email = str[1], dob = str[2], IMEI = str[3], phone = str[4], ImagePath = str[5];
File sourceFile = new File(ImagePath);
Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists());
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
String filename = ImagePath.substring(ImagePath.lastIndexOf("/") + 1);
/**
* OKHTTP2
*/
// RequestBody requestBody = new MultipartBuilder()
// .type(MultipartBuilder.FORM)
// .addFormDataPart("member_id", memberId)
// .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
// .build();
/**
* OKHTTP3
*/
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
.addFormDataPart("result", "my_image")
.addFormDataPart("name", name)
.addFormDataPart("email", email)
.addFormDataPart("dob", dob)
.addFormDataPart("IMEI", IMEI)
.addFormDataPart("phone", phone)
.build();
Request request = new Request.Builder()
.url(BASE_URL + "signup")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
res = response.body().string();
Log.e("TAG", "Response : " + res);
return res;
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e("TAG", "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
Log.e("TAG", "Other Error: " + e.getLocalizedMessage());
}
return res;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (progressDialog != null)
progressDialog.dismiss();
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("message").equals("success")) {
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
SharedPreferences settings = getSharedPreferences("preference", 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", jsonObject1.getString("name"));
editor.putString("userid", jsonObject1.getString("id"));
editor.putBoolean("hasLoggedIn", true);
editor.apply();
new UploadContactTask().execute();
startActivity(new Intent(SignupActivity.this, MainActivity.class));
} else {
Toast.makeText(SignupActivity.this, "" + jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(SignupActivity.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
}

OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS).build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("File", path.getName(),RequestBody.create(MediaType.parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),path))
.addFormDataPart("username", username)
.addFormDataPart("password", password)
.build();
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
result = response.body().string();
Click here to know how to receive the data in server for this request

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

How to send the fcm notifications using FCM server using http API with cloud functions

all I need to send the notifications for an app which contains 2 firebase database. from one firebase database I am sending notifications to an app. But app is not receiving the notifications
i have the same problem but resolve using this code
implement this library
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
static OkHttpClient mClient;
static JSONArray jsonArray;
static Context context;
static String messageStr = "";
public static void sendNotification(Context mContext,String mMessage,final JSONArray jsonArray1) {
mClient = new OkHttpClient();
context = mContext;
messageStr = mMessage;
jsonArray = jsonArray1;
new MyTask().execute();
}
static class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject root = new JSONObject();
JSONObject notification = new JSONObject();
notification.put("text", messageStr);
notification.put("title", "Cell Command");
notification.put("line1", R.mipmap.ic_launcher);
notification.put("line2", "high");
root.put("to", jsonArray.get(i));
root.put("data", notification);
String result = postToFCM(root.toString());
Log.d("Main Activity", "Result: " + result);
return result;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject resultJson = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
static String postToFCM(String bodyString) throws IOException {
final String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
final MediaType JSON
= MediaType.parse("application/json");
RequestBody body = RequestBody.create(JSON, bodyString);
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization", "key=" + "put your firebase legacy key")
.build();
Response response = mClient.newCall(request).execute();
return response.body().string();
}
inside jsonarray put your device token
hope this will help you.

Each time getting SocketTimeOut Exception while uploading an image

I have added a screen in my app in which a user uploads image from gallery or camera with some details and send it to server but the problem is this when I click on submit button each time I got "SocketTimeOutException" but mail sent to server. Please help.
I was able to upload form earlier but not now. What is the problem I am not able to get.
Code:
private void execMultipartPost() throws Exception {
RequestBody requestBody;
if (filePath != null) {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
fileBody = RequestBody.create(MediaType.parse(contentType), file);
filename = "file_" + System.currentTimeMillis() / 1000L;
Log.d("TAG", "execMultipartPost: " + filePath);
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("destination_type", selectedDescription)
.addFormDataPart("admin_id", admin_id)
.addFormDataPart("date", txtDate)
.addFormDataPart("time", txtTime)
.addFormDataPart("description", txtDescription)
.addFormDataPart("image", filename + ".jpg", fileBody)
.addFormDataPart("user_id", user_id)
.addFormDataPart("api_token", api_token)
.build();
} else {
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("destination_type", selectedDescription)
.addFormDataPart("admin_id", admin_id)
.addFormDataPart("date", selectdate.getText().toString())
.addFormDataPart("time", selecttimehr.getText().toString())
.addFormDataPart("description", description.getText().toString())
.addFormDataPart("image", "null")
.addFormDataPart("user_id", user_id)
.addFormDataPart("api_token", api_token)
.build();
}
okhttp3.Request request = new okhttp3.Request.Builder()
.url(Constansts.LETS_MELDEN)
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
Toast.makeText(getActivity(), getResources().getString(R.string.txt_error_occured), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ResponseBody responseBody = response.body();
String content = responseBody.string();
Log.e("TAG", "pic upload " + content);
JSONObject jsonObject = new JSONObject(content);
if (jsonObject.has("success")) {
Toast.makeText(getActivity(), "mail sent successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
description.setText(" ");
txt_picture_preview.setImageResource(android.R.color.transparent);
selecttypedec.setSelection(0);
progressDialog.dismiss();
// Log.d("TAG", "response of image: " + response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}

Android: file extension is undefined in the response body after uploading a file to server

I am using the following code for sending files (pdf,docx,pptx etc) from user to user in a chatting application.
public class UploadFile extends AsyncTask<String, Void, String> {
protected MessageModel mMessage;
File file ;
String mimeType = "";
public UploadFile(MessageModel msg, File file) {
super();
this.mMessage = msg;
this.file = file;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String responseBodyText = null;
mimeType = mMessage.getMsgFileType();
MediaType MEDIA_TYPE = okhttp3.MediaType.parse(mimeType);
OkHttpClient client = new OkHttpClient();
try {
RequestBody req = new okhttp3.MultipartBody.Builder()
.setType(okhttp3.MultipartBody.FORM)
.addFormDataPart("chatFileUpload", file.getName(), RequestBody.create(MEDIA_TYPE, file)).build();
Request request = new Request.Builder()
.header("Authorization", "Bearer "+Constants.AUTH_TOKEN)
.addHeader("User-Agent", Constants.USER_AGENT)
.url(urlforFileUpload)
.post(req)
.build();
Response response = null;
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Okhttp Error: " + response);
} else {
responseBodyText = response.body().string();
Log.d("PrintResponseBody", responseBodyText); // Print the response body here
}
} catch (IOException e) {
e.printStackTrace();
}
return responseBodyText;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject msgFiles = new JSONObject();
if (result != null) {
try {
JSONObject responseObject = new JSONObject(result);
msgFiles.put("filename", responseObject.get("fileName"));
msgFiles.put("mimetype", responseObject.get("mimetype"));
msgFiles.put("filepath", responseObject.get("fileUploadPath"));
Log.d("PrintFileUploadPath", String.valueOf(responseObject.get("fileUploadPath")));
// Print the response upload file path with file name and extension;
//.... do other stuffs....
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In the logcat, I'm getting extension as 'undefined' instead of proper extension name (.docx, .pptx etc). Can someone tell me which might cause this kind of behavior? Is it appropriate? If yes, how am I supposed to check which type of file user is receiving from server response?
An example of response I'm getting using debugger:
{
"status":"true",
"fileName":"1490691261587.undefined",
"fileUploadPath":"/uploads/chat_upload/1490691261587.undefined",
"mimetype":"file/file",
"msg":"File is uploaded successfully",
"downloadLink":"<a target=\"_blank\" href=\"/uploads/chat_upload/1490691261587.undefined\">New-Text-Document.txt909.txt</a>"
}
Thanks in advance.

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