Each time getting SocketTimeOut Exception while uploading an image - android

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();
}
}
});
}
});
}

Related

how to upload multiple files in android studio by okhttps only last file uploaded

I am uploading the multiple files to the server by using okhttps 3
but it always uploading the last file but not all files
my code is below
Explanation code:-
1.get user id form shared preference
2.create okhttps client
3 check the files are not null
4.create a multipartbody to add parameter and data
5.create a for loop attach the files in parameter
6.call request body and getting the response
public static void TaskAdd(final Activity activity, final String task_title, final String employees, final String priority, final String add_due_date, final String task_detail, final File[] file, final FragmentManager fragmentManager, final Dialog dialog) {
dialog.show();
Log.d(TAG, "sendImage: Enter");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
final String UserId = settings.getString("UserId", "");
OkHttpClient client = new OkHttpClient();
Request request;
// MultipartBody requestBody;
if (file != null) {
MultipartBody.Builder body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("task_title", task_title)
.addFormDataPart("employees", employees)
.addFormDataPart("priority", priority)
.addFormDataPart("add_due_date", add_due_date)
.addFormDataPart("task_detail", task_detail)
.addFormDataPart("user_id", UserId);
// body.addFormDataPart("files", file[i].getName(), RequestBody.create(MediaType.parse("Image/*"), file[i]));
// MultipartBody.Builder body2[]=new MultipartBody.Builder[file.length];
//
// for (int i=0;i<file.length;i++) {
// body2[i]= body.addFormDataPart("files", file[i].getName(), RequestBody.create(MediaType.parse("Image/*"), file[i]));
// }
for (int i = 0; i < file.length; i++) {
Log.d(TAG, "TaskAdd: File " + file[i]);
if (file[i].exists()) {
Log.d(TAG, "TaskAdd: "+i);
//body.addPart()
body.addFormDataPart("files", file[i].getName(), RequestBody.create(MediaType.parse("Image/*"), file[i]));
body.addFormDataPart("files", file[i].getName(), RequestBody.create(MediaType.parse("Image/*"), file[i]));
Log.d(TAG, "TaskAdd: "+ body.getClass().getName());
} else {
Log.d(TAG, "TaskAdd: No file found");
}
}
MultipartBody requestBody = body.build();
request = new Request.Builder().url("http://www.****.com/web/aagam/public/add_update_tasks").post(requestBody).build();
} else {
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("task_title", task_title)
.addFormDataPart("employees", employees)
.addFormDataPart("priority", priority)
.addFormDataPart("add_due_date", add_due_date)
.addFormDataPart("task_detail", task_detail)
.addFormDataPart("user_id", UserId)
.build();
request = new Request.Builder().url("http://www.****.com/web/aagam/public/add_update_tasks").post(body).build();
}
client.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(okhttp3.Call call, IOException e) {
dialog.dismiss();
Log.d(TAG, "OK HTTP 3.0 onFailure: ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Server Speed Slow please Try After SomeTime", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(okhttp3.Call call, final okhttp3.Response response) throws IOException {
dialog.dismiss();
final String responseBody = response.body().string().toString();
Log.d(TAG, "response " + responseBody);
activity.runOnUiThread(new Runnable() {
public void run() {
try {
JSONObject jsonObject = new JSONObject(responseBody);
String success = jsonObject.getString("success");
String message = jsonObject.getString("message");
if (success.equals("1")) {
Toast.makeText(activity, "Task added successfully", Toast.LENGTH_SHORT).show();
fragmentManager.popBackStack();
} else {
if (message.equalsIgnoreCase("Task added successfully")) {
Toast.makeText(activity, "Successful add task", Toast.LENGTH_SHORT).show();
fragmentManager.popBackStack();
} else {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
You are overwriting same file by passing same name,change it too file[] OR Pass as file1 and file2
for (int i = 0; i < file.length; i++) {
Log.d(TAG, "TaskAdd: File " + file[i]);
if (file[i].exists()) {
Log.d(TAG, "TaskAdd: "+i);
//body.addPart()
body.addFormDataPart("files["+i+"]", file[i].getName(), RequestBody.create(MediaType.parse("Image/*"), file[i]));
Log.d(TAG, "TaskAdd: "+ body.getClass().getName());
} else {
Log.d(TAG, "TaskAdd: No file found");
}
}

http file upload with post body

I am trying to Upload file along with JSON post body. I have tried something like this:
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("data", uploadFileName[1], RequestBody.create(MEDIA_TYPE_JPEG, file))
.addFormDataPart("name", uploadFileName[1])
.addFormDataPart("body",postBody)
.build();
NOTE: Above code works if I want to upload file without post body by removing
.addFormDataPart("body",postBody)
also I have tried to create ByteOutputArray of both file and post body and tried to create a ResquestBody.
Something like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment;filename=\"" + uploadFileName + "\"\r\n").getBytes("UTF-8"));
baos.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes("UTF-8"));
byte[] buffer = new byte[102400];// 100KB
int read = imageInputStream.read(buffer);
while (read >= 0) {
baos.write(buffer);
read = imageInputStream.read(buffer);
}
baos.write(("\r\n").getBytes("UTF-8"));
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment; name=\"" + fileNameText + "\"\r\n\r\n").getBytes("UTF-8"));
baos.write((postData).getBytes("UTF-8"));
baos.write(("\r\n").getBytes("UTF-8"));
baos.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
baos.flush();
MediaType MEDIA_TYPE_JPEG = MediaType.parse(fileType);
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JPEG,baos.toByteArray());
But nothing is working. Please help.
Try the code below:
private void chooseImageFile(){
Intent intent = new Intent() ;
intent.setType("image/*") ;
intent.setAction(Intent.ACTION_GET_CONTENT) ;
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri imagepath = data.getData() ;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagepath) ;
uploadimage.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
byte[] imagebyte = byteArrayOutputStream.toByteArray() ;
String encodeString = Base64.encodeToString(imagebyte, Base64.DEFAULT) ;
return encodeString ;
}
private void callImageUpload() {
String image_name = imagename.getText().toString().trim() ;
String bitmap_string = getStringImage(bitmap) ;
OkHttpClient image_upload_client = new OkHttpClient() ;
RequestBody postbody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", bitmap_string)
.addFormDataPart("name", image_name)
.build() ;
Request request = new Request.Builder().url(url).post(postbody).build() ;
setProgressDialouge();
image_upload_client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
progressDialog.dismiss();
String json_string = response.body().string() ;
try {
JSONObject main_obj = new JSONObject(json_string);
final String msg = main_obj.getString("response");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Multipart
#POST("/api/index.php?tag=sendFile")
Call<Object> sendCurrentFileAPI(
#Part("file") RequestBody designation, #Part MultipartBody.Part file);
and I am using following method for uploading file in my Activity
MultipartBody.Part multipartBody = null;
try {
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadingCurrentFile);
multipartBody = MultipartBody.Part.createFormData("file", uploadingCurrentFile.getName(), requestFile);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), requestBody +"");
mService.sendCurrentFileAPI( selectedDesignationValueRequestBody, multipartBody).enqueue(new Callback<Object>() {
#Override
public void onResponse(#NonNull Call<Object> call, #NonNull Response<Object> response) {
if (response.isSuccessful()) {
}
#Override
public void onFailure(#NonNull Call<Object> call, #NonNull Throwable t) {
}
});
Also I am using https://github.com/spacecowboy/NoNonsense-FilePicker for file picker

Encrypt URL Issue in OKHttp

Here Issue is I have to pass the parameter in the URL API but issue is json works in Postman-->Body-->raw
by passing parameters:
{"from":"abc","to":"pqr","amount":"10000"}
result is:
{
"errFlag": "0",
"errMsg": "Success",
"result": "1745738346.397"
}
But same thing we pass in OkHttp we get the other result
here is my code Okhttp:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isNetworkAvailable()) {
RequestBody formBody = new FormBody.Builder()
.add("from", "abc")
.add("to", "pqr")
.add("amount", "10000")
.build();
try {
post(Baseurl, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Log.e("res", " " + res);
try {
JSONObject jsonObject=new JSONObject(res);
String errFlag=jsonObject.getString("errFlag");
if(errFlag.equals("0")){
String a=jsonObject.getString("result");
Log.e("hello........",a);
}else{
Log.e("Error", "Wrong");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// you can access all the UI componenet
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
}
}
});
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
Output is:
{"errNum":"404","errFlag":"1","errMsg":"Some fields are missing"}
I just want errFlag=0 then pass the result else not.
Appreciate for help
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
formBody.add("version", version);
formBody.add("device_id", device_id);
formBody.add("platform", "android");
RequestBody body = formBody.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
result = response.toString();
} else {
}
result = response.body().string();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
Try with this code if it helps you then I ll give you one generic class for this.
Try as follows,
String postBodyParamsJson = "{\"from\":\"abc\",\"to\":\"pqr\",\"amount\":\"10000\"}";
RequestBody body = RequestBody.create(JSON, postBodyParamsJson);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();

Multiple OkHttp newCall not executing at once

So I will be making multiple GET requests and would love for them to execute all at once. However, as it is right now I have to hit the sign in button twice for the second newCall to go off. I would prefer if more newCall went off. But looking at it, the second newCall needs the response from the first one before it can. Is there a way that once the first gets the response, the second one executes instead of having to hit the sign in button twice?
Button code:
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (authPreferences.getUser() != null && authPreferences.getToken() != null) {
System.out.println(authPreferences.getToken());
doCoolAuthenticatedStuff();
try {
run();
} catch (Exception e) {
e.printStackTrace();
}
//new RetrieveFeedTask().execute();
} else {
chooseAccount();
}
}
});
run() code
public void run() throws Exception {
Request request = new Request.Builder()
.url(API_URL + authPreferences.getToken())
.build();
client.newCall(request).enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
try
{
String token = response.body().string();
JSONObject json = new JSONObject(token);
commatoken = json.getString("access_token");
} catch (JSONException e)
{
}
// commatoken = response.body().string();
// System.out.println(commatoken);
}
});
final Request dataRequest = new Request.Builder()
.header("content-type", "application/x-www-form-urlencoded")
.header("authorization", "JWT "+ commatoken)
.url(ChffrMe_URL).build();
client.newCall(dataRequest).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response responseMe) throws IOException {
if (!responseMe.isSuccessful()) throw new IOException("Unexpected code " + responseMe);
Headers responseHeaders = responseMe.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
try
{
String myInfo = responseMe.body().string();
JSONObject json = new JSONObject(myInfo);
commaMyInfo = json.getString("points");
} catch (JSONException e)
{
}
runOnUiThread(new Runnable() {
#Override
public void run() {
responseView.setText("Comma Points: " +commaMyInfo);
}
});
//responseView.setText(responseMe.body().string());
//System.out.println(responseMe.body().string());
}
});
}

Image upload using okHttp

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

Categories

Resources