receiving JSONobject allways failed with Voley - android

I have a problem when I try to use volley to communicate with a server (I created the server, so I can change a thing here too).
So when I use the stringRequest I have this problem:
my string contains 2 quotes, for example, the string looks like this: ""something""
while I send "something" and when I try to use this data like
if (response == "\"something\"")
do something
that doesn't work. I just can't use this string normally.
And when I try to use JsonObjectRequest I don't know why but I allways have this issue:
org.json.JSONException: Value {"name":"nofind"} of type java.lang.String cannot be converted to JSONObject
I tried to send this :
"{\"name\":\"nofind\"}",
"{'name':'nofind'}",
"{name:\"nofind\"}",
"{name:'nofind'}"
But It's always the same problem. I don't know why.
So please, if someone can help me. I will be very grateful
EDIT :
here my code :
JsonObjectRequest :
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL_SERVER+URL_IMAGE,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
resultsTextView.setText(response.toString());
snackbar.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
resultsTextView.setText(R.string.ErrorServor);
snackbar.dismiss();
}
}){
#Override
public byte[] getBody(){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
faceBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
faceBitmap.recycle();
return byteArray ;
}
#Override
public String getBodyContentType() {
return "image/jpeg";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
String request:
StringRequest request = new StringRequest(Request.Method.POST, URL_SERVER + URL_IMAGE,
this, this){
#Override
public byte[] getBody() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
faceBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
faceBitmap.recycle();
return byteArray ;
}
#Override
public String getBodyContentType() {
return "image/jpeg";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
resultsTextView.setText(R.string.ErrorServor);
snackbar.dismiss();
}
#Override
public void onResponse(String response) {
try {
if (response != "nofind")
{
resultsTextView.setText(response);
NoButton.setVisibility(View.VISIBLE);
YesButton.setVisibility(View.VISIBLE);
}
else {
resultsTextView.setText(R.string.NoBack);
}
resultsTextView.setText(obj.toString());
} catch (JSONException e) {
e.printStackTrace();
System.out.println(e);
}

For each people who have the same problem as me.
To establish a communication between a WCF server and an Android application with Volley.
For the StringRequest the solution is written above.I just had to use .equals(MyString) in place of ==MyString.
But for the JsonObjectRequest the problem was on the server. In the BodyStyle parameter.
the Solution is I had to Wrappe Only the response.
So this is the function who worked for me.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/NewUser",BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
dynamic NewUser(User user);
More information About the BodyStyle here :
RESTful web service body format

Related

Volley Post Request ClientError

I'm trying to send a POST Request with Volley to my server but it didnt work.
My GET-Requests are working fine and i also used postman to check if my rest service at the server works correctly.
I'm always getting a ClientError:
com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:190)
com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
I saw many different solutions here, but none of them worked out for my problem.
My StringRequest looks like this:
StringRequest addOrder = new StringRequest(
Request.Method.POST,
"http://myservice/rest/order",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String success = "DONE";
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String test = error.toString();
//Log.e("Rest Response", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(clickedCocktail);
oos.flush();
}
catch(IOException ioe){
//Do Stuff by Exception
String exStr = ioe.getMessage();
}
return bos.toByteArray();
}
};
requestQueue.add(addOrder);
}

Uploading signaturepad bitmap to remote server

I am working on an Android app that includes a signaturepad.
I would like to upload the resulting bitmap to a remote server.
I havenĀ“t found any resources that show how to manage this bitmap and how to convert it to a uploadable format.
This is the function that gets the signaturepad bitmap, and the needed function to upload it to a remote server:
btnFirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
uploadBitmap(signatureBitmap);//WHAT TO DO WITH THIS...
}
});
I have solved it as follows, using the Volley Library:
private void uploadBitmap() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Uploading Signature...");
dialog.setCancelable(false);
jsonObject = new JSONObject();
Bitmap image = signatureBitmap;
dialog.show();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
try {
jsonObject.put(Utils.imageName, numero);
jsonObject.put(Utils.image, encodedImage);
} catch (JSONException e) {
Log.e("JSONObject Here", e.toString());
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Utils.urlUpload, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("Message from server", jsonObject.toString());
dialog.dismiss();
// messageText.setText("Image Uploaded Successfully");
Toast.makeText(getActivity(), "Signature Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Message from server", volleyError.toString());
dialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity()).add(jsonObjectRequest);
}
What is the process? For C#, I'm trying to get image and send by HTTP client, perhaps, on the server only get a blank image, this is the code on the Xamarin Forms:
<forms:SignaturePadView
BackgroundColor="Transparent"
StrokeColor="Blue"
StrokeWidth="3"
HeightRequest="250"
Name="Signature"
/>
And in the View Model:
Stream image = await Signature.GetImageStreamAsync(SignatureImageFormat.Png);
To send:
var bytes = new byte[image.Length];
await image.ReadAsync(bytes, 0, (int)image.Length);
string imageBase64 = Convert.ToBase64String(bytes);
On the request:
try
{
var client = new HttpClient();
var response = await client.PostAsync(urlBase,
new StringContent(string.Format(
"imgSign={0}",
imageBase64),
Encoding.UTF8, "application/x-www-form-urlencoded"));
if (!response.IsSuccessStatusCode)
{
return response.ToString();
}
else
{
var response = await response.Content.ReadAsStringAsync();
return response;
}
}
catch
{
return null;
}
Server receives by a Post Request and using file_puts_contents to send image on folder:
if (isset ($image = $_POST['imgSign'])) {
$dateNow = date("d-m-Y");
$imageName = 'Id'.$dateNow;
$image = $_POST['imgSign'];
$path = "../images/$imageName.png";
if(file_put_contents($path,base64_decode($image))){
...update DB
}
}

Uploading a File using Volley API via PUT method

I've been looking for a way to upload a file using Volley API using the PUT method. All I've seen so far are through MultiPart POST method which aren't applicable to my case.
Assuming I can't change anything on the server side and I'm stuck with using PUT. How do I achieve this in volley?
Note that I only have the url where to upload the file and the file itself.
For uploading image file add the following functions to your StringRequest object.
Here outputFileUri is the Uri of the file which you want to upload.
#Override
public String getBodyContentType() {
return "image/jpeg";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = mContext.getContentResolver().openInputStream(outputFileUri);
byte[] b = new byte[8192];
for (int readNum; (readNum = inputStream.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
inputStream.close();
return bos.toByteArray();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return null;
}
use the basic concept of PUT method
url = "your URL";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("name", "file_name");
return params;
}
}; RequestQueue queue = Volley.newRequestQueue(this);
queue.add(putRequest);

com.android.volley.NoConnectionError: java.net.SocketException: sendto failed: EPIPE (Broken pipe)

I have a simple task of uploading a base 64 encoded image to a server using Volley.
My server does not do anything. It just returns a 200 status code. But I always end up with this error even after the server returns 200. I tried some of the other solutions online but nothing seems to work.
private void uploadImage(){
obj = new JSONObject();
try {
obj.put("image", getStringImage(bitmap));
} catch (Exception e) {
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, UPLOAD_URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("Message from server", jsonObject.toString());
Toast.makeText(getApplication(), "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Message from server", volleyError.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
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;
}
I know this is late , but for me , the solution is to increase the http max post size in your server.for me I using spring boot with embedded tomcat server so the solution is to add the below line to your application.properties file:
server.tomcat.max-http-post-size=10000000
above I have set it to 10MB , another way of doing this is through java code as pointed by the answer in this link
Increase HTTP Post maxPostSize in Spring Boot
hope that helps you

Send image via JsonObjectRequest Volley in Android?

I have a POST method send a JsonObject via Volley:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, postBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
log("success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
log("" + error);
}
});
request.setRetryPolicy(new DefaultRetryPolicy(10000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(this).add(request);
With postBody:
JSONObject postBody = new JSONObject();
try {
postBody.put("name", "rome");
//postBody.put("image", file?);
} catch (JSONException e) {
log("" + e);
}
I want to send a image file with key "image" above. This file type is the same with file of form-data in PostMan (not url of file).
Is there anyway to do it? Thanks.

Categories

Resources