convert image to file and send to volley and json url - android

I am trying to update a profile with an image and other details using Volley.
I have to convert the image file and send it to the url as parameter.
I also have to parse all the other details to update the profile.
How can I update the profile image?
url = "http://192.168.1.30:1021/mobileapi/profile_update.html?&user_id="+user+"&firstname="+First.getText().toString()+
"&lastname="+last.getText().toString()+"&secondaryemail="+sEmail.getText().toString()+
"&phonemobile="+mob.getText().toString()+"&aboutus="+work.getText().toString()+"&phonework="+phone.getText().toString()+
"&skypeid="+skypeid.getText().toString()+"&gender="+gender+"&smtp_password="+mpass.getText().toString()+"&image="+fos;
url=url.trim().replaceAll("\\s+","");
System.out.println("url" + url);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.dismiss();
queue = Volley.newRequestQueue(getActivity());
request = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
System.out.println("updaa" + response.toString());
JSONObject update = response.getJSONObject(0);
int httpcode = Integer.parseInt(update.getString("status"));
if (httpcode == 200) {
String mess = update.getString("message");
Toast.makeText(getActivity(), mess, Toast.LENGTH_LONG).show();
int userid = Integer.parseInt(update.getString("user_id"));
String fname = update.getString("firstname");
String lname = update.getString("lastname");
String mail = update.getString("email");
String smail=update.getString("secondary_email");
/* String ph= String.valueOf(Integer.parseInt(update.getString("phone_work")));
String phone= String.valueOf(Integer.parseInt(update.getString("phone_mobile")));*/
String skype_id = update.getString("skype_id");
String user_title = update.getString("user_title");
String imgUrl = update.getString("image");
editor.putString("name", fname);
editor.putString("userid", String.valueOf(userid));
editor.putString("lname",lname);
editor.putString("mail",mail);
editor.putString("skype",skype_id);
editor.putString("image",imgUrl);
// editor.putString("phone", String.valueOf(ph));
editor.putString("work",user_title);
editor.putString("smail",smail);
// editor.putString("phone", String.valueOf(phone));
editor.commit();
} else {
JSONObject typ = response.getJSONObject(0);
String message = typ.getString("message");
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("result" + error.getLocalizedMessage()+"__"+error.getMessage());
Log.e("Volley", "Error");
}
}){
};
queue.add(request);
}
}
});
return view;
}
private void opengallery() {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == PICK_IMAGE_REQUEST && intent != null && intent.getData() != null) {
Uri uri = intent.getData();
try {
/*Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));*/
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
Log.d("TAG", String.valueOf(bitmap));
Bpro.setImageBitmap(bitmap);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(uri + ".png");
file = new File(extStorageDirectory, uri + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + uri);
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);
/* fos = new FileOutputStream(f);
fos.write(bitmapdata);*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON response
[{
"smtp_password":"abdul",
"status":"200",
"user_type":"2",
"skype_id":"skype",
"emp_id":"N0418",
"phone_work":"9864545454",
"image":"http:\/\/192.168.1.30:1021\/uploads\/Nandha\/profile_image\/180_200\/45571.png",
"lastname":"Rahman",
"firstname":"Abdul",
"user_title":"android",
"message":"Profile has been updated successfully",
"email":"4dZR9RLF#gmail.com",
"gender":"1",
"user_id":"45571",
"secondary_email":"abdul#gmail.com",
"phone_mobile":"9892545454"
}]

use this code ..it works for me .Its sends multipart images.
private void saveProfileDetails() {
// loading or check internet connection or something...
// ... then
String url = "http://51.76.27.90:8080/post/new/";
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
System.out.println("statuscode is " + response.statusCode);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message + " Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message + " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message + " Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", "a#a.com");
params.put("category", "product");
params.put("type", "product");
params.put("title", "i am done ");
params.put("content", "contentssssssssssssssssssssssss");
params.put("location", "Bangalore");
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("imageC", new DataPart("file_avatar.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), colorImage.getDrawable()), "image/jpeg"));
params.put("imageBW", new DataPart("file_cover.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), blackAndWhiteImage.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
and this is your VollySingleton function
/**
* Created by snehasish on 29/7/16.
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
/**
* Singleton volley to populate request into single queue.
*/
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
/**
* Private constructor, only initialization from getInstance.
*
* #param context parent context
*/
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruBitmapCache(mCtx);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
/**
* Singleton construct design pattern.
*
* #param context parent context
* #return single instance of VolleySingleton
*/
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
/**
* Get current request queue.
*
* #return RequestQueue
*/
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
/**
* Add new request depend on type like string, json object, json array request.
*
* #param req new request
* #param <T> request type
*/
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
/**
* Get image loader.
*
* #return ImageLoader
*/
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
if it helps pls make this answer as right!

Related

Volley sending empty images

onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
bitmapFrontIC = (Bitmap) data.getExtras().get("data");
frontICImageView.setImageBitmap(bitmapFrontIC);
}else if(requestCode == REQUEST_CAPTURE_BACKIC && resultCode == RESULT_OK){
bitmapBackIC = (Bitmap) data.getExtras().get("data");
backICImageView.setImageBitmap(bitmapBackIC);
}
}
submitbuttonOnClick:
public void submitOnClick(View view){
Log.d("Submit clicked", "Submit Clicked");
if(icNumber.getText().toString().length() > 0 && bitmapFrontIC != null && bitmapBackIC != null){
uploadBitmap(bitmapFrontIC,bitmapBackIC);
}else{
Toast.makeText(getApplicationContext(), "Please fill up all the fields", Toast.LENGTH_SHORT).show();
}
}
GetFileDataFromDrawable:
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
uploadBitMap:
private void uploadBitmap(final Bitmap bitmapFrontIC, final Bitmap bitmapBackIC) {
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.API_URL + "/users/upload-ic",
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
loading.dismiss();
try {
JSONObject obj = new JSONObject(new String(response.data));
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String errorResponse = new String(networkResponse.data);
try {
JSONObject errorObject = new JSONObject(errorResponse);
if(errorObject.has("error")){
Toast.makeText(ICVerificationActivity.this, errorObject.getString("message"),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Print Error!
Log.d("JSON ERROR", errorResponse);
}
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("icno", icNumber.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "multipart/form-data");
headers.put("Authorization", "Bearer " + "abcd");
return headers;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imageName = System.currentTimeMillis();
params.put("icFront", new DataPart("FrontIC_" + imageName + ".png", getFileDataFromDrawable(bitmapFrontIC)));
params.put("icBack", new DataPart("BackIC_"+imageName + ".png", getFileDataFromDrawable(bitmapBackIC)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
loading.show();
}
I am trying to call the POST request by inputting three items to the body:
a) text
b) camera_image1
c) camera_image2
I am able to display the captured image from camera in the imageview which means the bitmap is working. However, when I want to upload to the server, the server returns that the images are empty. Am I doing it wrongly?

How to I send POST parameters in this android studio code [duplicate]

This question already has answers here:
Sending POST data in Android
(17 answers)
Closed 5 years ago.
I'm new to android and learning it now. I'm working on an application where I was able to get response form a get request successfully. Now I want to execute a POST request with a single parameter this is what I've came up with so far:
public class BGTask extends AsyncTask<String, String, String > {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
String color = "null";
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
//I want to pass the id parameter
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
int status = parentObject.getInt("status");
if(status == 1) {
color = parentObject.getString("bgcolor");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return color;
}
}
The variable color is in hex code i.e #FF0089
** Use volley library for GET , POST and network calls it's very simple and efficient **
First create AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
Second make POST request
public void Send() {
final String First = "";
final String Second = "";
StringRequest stringRequest = new StringRequest(Request.Method.POST, CREATEORDER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
JSONObject jObj = null;
try {
jObj = new JSONObject(response);
String success = jObj.getString("success");
String errorMessage = jObj.getString("message");
if (success.equals("")) {
Intent intent = new Intent(SendGiftActivity.this, PayScreenActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(SendGiftActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SendGiftActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_FIRST_PARAMETERS, First);
params.put(KEY_SECOND_PARAMETER, Second);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Include volley library
compile 'com.android.volley:volley:1.0.0'
Don't forget to add android:name=".AppController" in application tag of manifest file

Volley post request not sending data properly

I'm trying to send a base64 encoded string to a server over volley but its not sending properly. When i use httpbin this is the response
"args": {},
I/System.out: "data": "",
I/System.out: "files": {},
I/System.out: "form": { "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmN...(image base64)
I/System.out: },
where the image data is in the form. However i need it in data.
public static String rawOutput = "dadsdas";
private Button buttonChoose;
private Button buttonUpload;
public String image;
private ImageView imageView;
private Button postText;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="https://httpbin.org/post";
private String KEY_IMAGE = "Content-Type";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_image);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
postText = (Button) findViewById(R.id.postText);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
System.out.println(imageBytes);
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() throws JSONException {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
// JSONObject jsonBody = new JSONObject();
// jsonBody.put(getStringImage(bitmap), "");
//final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
System.out.println(s);
Toast.makeText(PostImage.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
String json = null;
NetworkResponse response = volleyError.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode){
case 400:
json = new String(response.data);
if(json != null) System.out.println(json);
System.out.println(json.getClass().getSimpleName());
break;
}
//Additional cases
}
Toast.makeText(PostImage.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}){
// #Override
// public String getBodyContentType() {
// return "text/plain; charset=utf-8";
// }
// #Override
// public byte[] getBody() {
// byte[] body = new byte[0];
// try {
// body = ("/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVz.......(image data here)");
//
//} catch (UnsupportedEncodingException exception) {
// Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
//return null;
//}
return httpPostBody.getBytes();
}
// #Override
// public String getBody() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// String params= "";
// params= image;
// return params;
//
// }
// #Override
// protected Map<String, String> getParams() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// Map<String,String> params = new Hashtable<String, String>();
// params.put("", image);
// return params;
// }
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
System.out.println(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 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 filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
try {
uploadImage();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void postText(View v) {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://api.getquesto.com:8080/upload";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Text:", "A leaf is an organ of a vascular plant and is the principal lateral appendage of the stem.[1] The leaves and stem together form the shoot.[2] Leaves are collectively referred to as foliage, as in \"autumn foliage.\"[3][4]\n" +
"\n" +
"\n" +
"Diagram of a simple leaf.\n" +
"Apex Midvein (Primary vein) Secondary vein. Lamina. Leaf margin Petiole Bud Stem\n" +
"Although leaves can be seen in many different textures and sizes, typically a leaf is a thin, dorsiventrally flattened organ, borne above ground and specialized for photosynthesis. In most leaves, the primary photosynthetic tissue, the (palisade mesophyll), is located on the upper side of the blade or lamina of the leaf[1] but in some species, including the mature foliage of Eucalyptus,[5] palisade mesophyll is present on both sides and the leaves are said to be isobilateral. Most leaves have distinctive upper (adaxial) and lower (abaxial) surfaces that differ in colour, hairiness, the number of stomata (pores that intake and output gases), epicuticular wax amount and structure and other features.\n" +
"\n" +
"Broad, flat leaves with complex venation are known as megaphylls and the species that bear them, the majority, as broad-leaved or megaphyllous plants. In others, such as the clubmosses, with different evolutionary origins, the leaves are simple, with only a single vein and are known as microphylls.[6]\n" +
"\n" +
"Some leaves, such as bulb scales are not above ground, and in many aquatic species the leaves are submerged in water. Succulent plants often have thick juicy leaves, but some leaves are without major photosynthetic function and may be dead at maturity, as in some cataphylls, and spines). Furthermore, several kinds of leaf-like structures found in vascular plants are not totally homologous with them. Examples include flattened plant stems called phylloclades and cladodes, and flattened leaf stems called phyllodes which differ from leaves both in their structure and origin.[4][7] Many structures of non-vascular plants, such as the phyllids of mosses and liverworts and even of some foliose lichens, which are not plants at all (in the sense of being members of the kingdom Plantae), look and function much like leaves.");
final String mRequestBody = jsonBody.toString();
String json = null;
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(PostImage.this, response , Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","text/plain");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
does anyone know how to make it send through data?

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

How to do upload image with Volley library?

I have an image and I want to upload this image to my web service using Volley library, the problem is I'm looking for a how to do it but still haven't found.
I found this, but doesn't work to me: http://develop-for-android.blogspot.com.br/2014/01/using-volley-in-your-application.html
How can I do this ?
I'm trying this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
fotoPerfil = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
UploadoImageToServer upload = new UploadoImageToServer();
ApplicationController app = new UsuarioDAO().insert(usuario, upload.upload(fotoPerfil, em[0]), new UsuarioAdapter(){
#Override
public void usuarioIsAdded(Boolean result){
Log.i("Adicionou: ", result + "");
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);
public class UploadoImageToServer {
public String upload(String image,String nomeImagem){
Bitmap bitmap = BitmapFactory.decodeFile(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
return image_str;
}
}
/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, String uploadFile, final UsuarioAdapter listener) {
boolean insert = false;
HashMap<String, String> params = new HashMap<String, String>();
params.put("nome", u.getNome());
params.put("email", u.getEmail());
params.put("senha", u.getSenha());
params.put("tipo", "usuarios");
params.put("acao", "add");
params.put("device_tipo", "android");
params.put("device", AndroidReturnId.getAndroidId());
params.put("uploadedfile", uploadFile);
Log.i("URL: ", urlPost.toString());
ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("cod").equals("999")){
listener.usuarioIsAdded(true);
}else{
listener.usuarioIsAdded(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
}
});
return apc;
}
i am not much familier with volley, but give a try to the following code
//JSON Request
public MySampleImageUpload() {
JSONRequestResponse mResponse = new
JSONRequestResponse(mContext);
Bundle parms = new Bundle();
parms.putString("key_meail", "rojesh#demo.com");
parms.setFile("key_url", image_path);
mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
parms);
}
// In SetFile & getResponse code
package com.fartogram.utils;
import java.io.File;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;
public class JSONRequestResponse {
public JSONRequestResponse(Context cntx) {
mContext = cntx;
}
private final Context mContext;
private int reqCode;
private IParseListener listner;
private boolean isFile = false;
private String file_path = "", key = "";
public void getResponse(String url, final int requestCode,
IParseListener mParseListener) {
getResponse(url, requestCode, mParseListener, null);
}
public void getResponse(String url, final int requestCode,
IParseListener mParseListener, Bundle params) {
this.listner = mParseListener;
this.reqCode = requestCode;
Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (listner != null) {
listner.SuccessResponse(response, reqCode);
}
}
};
Response.ErrorListener eListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (listner != null) {
listner.ErrorResponse(error, reqCode);
}
}
};
if (!isFile) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, sListener,
eListener);
MyVolley.getRequestQueue().add(jsObjRequest);
} else {
if (file_path != null) {
File mFile = new File(file_path);
MultipartRequest multipartRequest =
new MultipartRequest(url,eListener, sListener, key, mFile, params);
MyVolley.getRequestQueue().add(multipartRequest);
}
}
}
public boolean isFile() {
return isFile;
}
public void setFile(String param, String path) {
if (path != null && param != null) {
key = param;
file_path = path;
this.isFile = true;
}
}
}
If it works for you mark it as right :)
You have to extend Request and use MultipartEntityBuilder if you wanna upload your image as a file.
public class ImageUploadWithVolley<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File yourImageFile;
protected Map<String, String> headers;
public ImageUploadWithVolley(String url, ErrorListener errorListener, Listener<T> listener, File imageFile) {
super(Method.POST, url, errorListener);
mListener = listener;
yourImageFile = imageFile;
addImageEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Accept", "application/json");
return headers;
}
private void addImageEntity() {
mBuilder.addBinaryBody("give your image name", yourImageFile, ContentType.create("image/jpeg"), yourImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String content = mBuilder.build().getContentType().getValue();
return content;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e){
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response){
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}

Categories

Resources