how to see json data send to server in volley in android - android

I'm sending json data to server successfully.But problem in sending image.
I try the following thing:-
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://toootapp.dreamsapps.com/ToootWebservice.asmx/SaveImage",
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.e("img Response",s.toString().trim());
//Disimissing the progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("onErrorResponse=",getIntent().getStringExtra("path"));
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
// Toast.makeText(SaveImageOnServerActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
// Log.e("Path=",getIntent().getStringExtra("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(new File(getIntent().getStringExtra("path")).getAbsolutePath());
String image = getStringImage(myBitmap);
//Getting Image Name
String name = "Computer";//editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("base64Image", image);
params.put("Tags", "Computer");
//returning parameters
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
So I just want to check which json string is going to server.
Is there any way I can see what json string in the following form
{
"base64Image": "",
"Email": "abc#gmail.com",
"MobileNo": "1234567890",
"Website": "www.gameneeti.com",
"Industry": "Computer"
}
I send.
I want to print in log this string.
Thanks.

Related

Android Volley request works on emulator but getting client error on the physical phone. guys please help me , I am new to this

Volley request is working just fine on the phone and emulator for the login activity but not for this one. See the error message and code below.
2021-02-20 22:23:25.695 29250-30267/com.bignerdranch.android.equipmentinspection E/Volley: [2336] BasicNetwork.performRequest: Unexpected response code 404 for https://sbmequipmentinspection.com/vehicleTable.php
2021-02-20 22:23:25.697 29250-29250/com.bignerdranch.android.equipmentinspection E/somethingWrong: com.android.volley.ClientError
private void uploadTOServer() {
String reg_url = "https://sbmequipmentinspection.com/vehicleTable.php";
final String loclaTime = android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", mVehicle.getDate()).toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(),"Thank you for submitting vehicle inspection",Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("somethingWrong", error.toString());
Toast.makeText( getContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
String image = getStringImage(mPhotoFile);
Map<String,String> params = new HashMap<String, String>();
params.put("id", mVehicle.getID().toString());
params.put("user", SavePreference.getPrefUserName(getActivity()));
params.put("date",loclaTime);
params.put("vehicleNumber",mVehicle.getEquipmentNumber());
params.put("mileageNumber", mVehicle.getMilage());
params.put("question1" , mQuestionBank[0].getStatus());
params.put("question2", mQuestionBank[1].getStatus());
params.put("question3" , mQuestionBank[2].getStatus() );
params.put("question4", mQuestionBank[3].getStatus());
params.put("question5", mQuestionBank[4].getStatus());
params.put("question6", mQuestionBank[5].getStatus());
params.put("question7", mQuestionBank[6].getStatus());
params.put("question8", mQuestionBank[7].getStatus());
params.put("question9", mQuestionBank[8].getStatus());
params.put("question10", mQuestionBank[9].getStatus());
params.put("question11", mQuestionBank[10].getStatus());
params.put("question12", mQuestionBank[11].getStatus());
params.put("question13", mQuestionBank[12].getStatus());
params.put("addInfo", mVehicle.getExtraInfo());
params.put("status", mVehicle.getStatus());
params.put("image", image);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
private String getStringImage(File photoFile) {
Bitmap bitmap = PictureUtils.getScaledBitmap(photoFile.getPath(),getActivity());
ByteArrayOutputStream ba = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,ba);
byte[] imagebyte = ba.toByteArray();
String encode = Base64.encodeToString(imagebyte, Base64.DEFAULT);
return encode;
}```
This is what I would do. Firstly before the return I would create a string to check the JSON format, String mRequestBody = jsonObject.toString(); After that i would extract that JSON and put it into an Application known as Postman, https://www.postman.com/ and test if it still works there, let me know what you find?

Volley doesnot connect with flask server

My java code is not connect with flask. It doesn't give any error or response. Program run infinitely.
When i try to connect it is not going on response or on error function. After completing function call it start running and never stop.
Java Code:
Button button;
RequestQueue rQueue;
String url ="http://127.0.0.1:5000/predict";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
rQueue = Volley.newRequestQueue(MainActivity.this);
}
public void predict(View view){
UploadTwoImages();
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void UploadTwoImages() {
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
final String imageOne = getStringImage(icon);
final ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Registration is in Process Please wait...");
pDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
pDialog.dismiss();
Log.d("JSONResult", s);
try {
JSONObject jObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("image", imageOne);
return parameters;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
90000,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.setShouldCache(false);
rQueue.add(request);
}
Flask Server Code:
#app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == "POST":
if request.files:
output={}
image = request.files["image"]
print(request.files)
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(image.filename))
print(image.filename)
image.save(file_path)
return str([1])
return "Error"
if __name__ == '__main__':
app.run(debug=True)
url = ipv4address:portNumber/apiName
In android manifest add following 2 lines and it works for me.
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET"/>

Upload image to server c# android

Well this might sound a question that has been asked few often times but I could not come with a solution for the same.I want to upload image to server C#, i got codes for how to send image but don't know exactly how to use it. Please correct my code if there is something wrong and any idea about server side code for the same correction.
ProgressDialog progressDialog = new ProgressDialog(AddPropertyThird.this);
progressDialog.setMessage("Uploading, please wait...");
progressDialog.show();
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes,Base64.DEFAULT);
//sending image to server
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(AddPropertyThird.this, "Some error occurred -> " + volleyError, Toast.LENGTH_LONG).show();
}
}) {
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("imageFile", imageString);
return parameters;
}
};
RequestQueue rQueue = Volley.newRequestQueue(AddPropertyThird.this);
rQueue.add(request);
}
});
}
Logcat error
[879] BasicNetwork.performRequest: Unexpected response code 500
02-09 12:33:24.106 2 E/volleyerror: com.android.volley.ServerError

Send byte[] from android volley to asp.net mvc

I am trying to upload an image from android to asp.net mvc webapp. I've the following code to upload image on android part -
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private String UPLOAD_URL ="UploadSignature?id=1";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private Bitmap bitmap;
private void uploadImage(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = getStringImage(bitmap);
String name = "firstImage";
Map<String,String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
In asp.net mvc controller-
[HttpPost]
public ActionResult UploadSignatureTwo(byte[] Data)
{
System.IO.File.WriteAllBytes( #"D:\test.jpg", Data);
}
But it says Data can not be null.
Any help?

Android Volley ECONNRESET

I try to use Volley library and upload image to server. This library should do this process in standalone mode, but have got following error message:
java.net.SocketException: sendto failed: ECONNRESET (Connection reset
by peer)
Is it maybe a server side misconfiguration?
I try to upload a jpeg image with this code:
private void uploadImage(){
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = getStringImage(bitmap);
String name = editTextName.getText().toString().trim();
Map<String,String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
just to be sure, you need to change your uploadImage() into something like this:
private void uploadImage(){
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
//here you use your custom multi-part-request as I suggested in the comment:
ImageUploadRequest imageUploadReq = new ImageUploadRequest(UPLOAD_URL,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
},
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, s , Toast.LENGTH_LONG).show();
}
}, yourImageFile);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(imageUploadReq);
}
Where your ImageUploadRequest class is defined as demonstrated in the accepted answer here like this:
public class ImageUploadRequest<T> extends Request<T> {
private static final String FILE_PART_NAME = "file";
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageToUpload;
protected Map<String, String> headers;
public ImageUploadRequest(String uploadURL, ErrorListener errorListener, Listener<T> listener, File imageFileToUpload){
super(Method.POST, uploadURL, errorListener);
mListener = listener;
mImageToUpload = imageFileToUpload;
//call the helper method to build the multipart entity
buildMultipartEntity();
}
#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 buildMultipartEntity(){
mBuilder.addBinaryBody(FILE_PART_NAME, mImageToUpload, ContentType.create("image/jpeg"), mImageToUpload.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#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);
}
}
I have made some minor adaptations of Upload an image using Google Volley to your specific situation. I hope this helps you and that others may also find it useful.
I usually get this error when I don't use url encoded queries.
Take a look URL encoding in Android

Categories

Resources