how can send JSON? - android

I'm trying to send a JSON to web service using Google Cloud API but keep getting the error below;
ERROR == 415
"E/Volley: [293] BasicNetwork.performRequest: Unexpected response code 415 for http://172.17.1.169:8080/api/save"
Here the code:
mTextMod.setText(text);
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("text", text);
jsonParam.put("language", "gl-ES");
jsonParam.put("voice", "Vocalizer Expressive Carmela Harpo 22kHz");
jsonParam.put("rate", null);
jsonParam.put("volume", "90");
System.out.println("patata ->" + jsonParam.toString());
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
jsonParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(),
Toast.LENGTH_LONG).show();
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
System.out.println(error.toString());
NetworkResponse networkResponse = error.networkResponse;
}
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
}
});
queue.add(jsonObjectRequest);

/**
* Pass request headers
*/
#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;
}
/**
*like below
*/
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("text", text);
jsonParam.put("language", "gl-ES");
jsonParam.put("voice", "Vocalizer Expressive Carmela Harpo 22kHz");
jsonParam.put("rate", null);
jsonParam.put("volume", "90");
System.out.println("patata ->" + jsonParam.toString());
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, jsonParam, new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_LONG).show();
System.out.println(response.toString());
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
System.out.println(error.toString());
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
}
})
{
/**
* Passing some request headers
*/
#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;
}
};
queue.add(jsonObjectRequest);

Related

Device ID is not going to the heasers

Im working on Registration using volley liabray.I want to send Device ID in header but it going null here is my code snippit.
Log.d("TAG", "Details:" + response);
String strMessage = response.optString("message");
String strDevice = response.optString("deviceID");
CryptoHandler cryptoHandler = new CryptoHandler();
String decryptMessage = cryptoHandler.decrypt(strMessage);
String decryptDevice = cryptoHandler.decrypt(strDevice);
Log.d("TAG","Decrypted Response:"+decryptMessage +decryptDevice);
// responseTV.setText("String Response : " + response.toString());
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// responseTV.setText(error.getMessage());
// Toast.makeText(RegisterActivity.this, "Error"+error, Toast.LENGTH_LONG).show();
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),
"Oops. Timeout error!",
Toast.LENGTH_LONG).show();
}
}
//This is for Headers If You Needed
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("DeviceId", ID);
return headers;
}
};
requestQueue.add(jsonObjectRequest);

Getting wrong response in volley

I am getting wrong response in volley while on the other hand postman getting correct response. Please help me where is the problem . Response i am getting from volley is "response= {"code":1020,"message":"Duplicate key not allowed","returnId":null}"
And in postman it is "{
"code": 1089,"message": "Activation Key sent in email, please activate your user/device","returnId": 438
}"
public void sendRegisterationReq("http://demo.innowi.com/v1/user/register",getJsonObject()) {
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, dataObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(context, "" + response.toString(), Toast.LENGTH_SHORT).show();
System.out.println("response= " + response.toString());
System.out.println(TAG + ":" + dataObj.toString());
try {
if (response.getString("code").equals("1020")){
Intent intent = new Intent(RegisterDeviceActivity.this,ActivateDeviceActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
if (volleyError instanceof NetworkError) {
message = "Network error!";
Log.d(TAG,message);
} else if (volleyError instanceof ServerError) {
message = "Server error!!";
Log.d(TAG,message);
} else if (volleyError instanceof AuthFailureError) {
message = "Auth failure error!";
Log.d(TAG,message);
} else if (volleyError instanceof ParseError) {
message = "Parsing error!";
Log.d(TAG,message);
} else if (volleyError instanceof NoConnectionError) {
message = "No connection error!";
Log.d(TAG,message);
} else if (volleyError instanceof TimeoutError) {
message = "timeout error !";
Log.d(TAG,message);
}
/*Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
System.out.println(TAG + ":Error: " + volleyError.getMessage());
System.out.println(TAG + ":" + volleyError.toString());*/
System.out.println(TAG + ":" + dataObj.toString());
}
}) {
/**
* Passing some request headers
* */
#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;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setTag("myRequest");
// Adding request to request queue
queue.add(jsonObjReq);
}
public JSONObject getJsonObject(){
JSONObject object = new JSONObject();
try {
if (username!=null && password !=null) {
object.put("username", username.getText().toString());
object.put("password", password.getText().toString());
object.put("deviceMacAddress", "90:B6:86:0D:CE:4F");
}
else
{
Toast.makeText(this, "Email/password should not be empty", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
you are the data which is already exist in your database so says duplicate key try different one or try to send all fields valid and different.

getting empty body while sending post request using volley Android

When I am making POST request call using JsonObjectRequest in volley then on certain wifi it is sending empty body. But it works fine with StringRequest POST request. It is working fine on all mobile networks.
I am using node.js server and expressjs/body-parser. When I am making POST request using Postman, everything works fine.
What is the error? If anyone wants to see code I can provide.
POST request using StringRequest
private void LoginUser(final String email,final String pass) {
try {
/*Map<String, String> params = new HashMap<String, String>();
params.put("username", email);
params.put("password", pass);
JSONObject jsonParams = new JSONObject(params);*/
final StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();
try
{
Log.i("Inside try", "yes");
JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");
Log.i("User name",jsonResponse.getString("name"));
Constants.setClinicName(jsonResponse.getString("name"));
String TokenDB=new JSONObject(response).getString("token");
//Toast.makeText(getApplicationContext(),TokenDB,Toast.LENGTH_LONG).show();
if(pd.isShowing())
{
pd.dismiss();
}
//Maintaining LogIn data till user clicks LogOut
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("Token",TokenDB);
//editor.putString("username", username);
editor.commit();
//Printing Token in Log in case of null token debugging
/*String status=manager.getPreferences(ClinicLogin.this,"token");
Log.d("token", status);
*/
Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}catch (JSONException ks)
{
ks.printStackTrace();
Toast.makeText(getApplicationContext(),
"Oops! The Username & Password Do Not Match. Please try again!",
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
if(pd.isShowing()) {pd.dismiss();}
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
}
else error.printStackTrace();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", email);
params.put("password", pass);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
7000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
POST call using JsonobjectRequest
private void LoginUser(String email,String pass) {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("username", email);
params.put("password", pass);
JSONObject jsonParams = new JSONObject(params);
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL, jsonParams,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
String TokenDB = response.getString("token");
JSONObject user=response.getJSONObject("user");
Constants.setClinicName(user.getString("name"));
//Constants.setTokenDB(TokenDB);
if(pd.isShowing())
{
pd.dismiss();
}
//Maintaining LogIn data till user clicks LogOut
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("Token",TokenDB);
//editor.putString("username", username);
editor.commit();
//Printing Token in Log in case of null token debugging
/*String status=manager.getPreferences(ClinicLogin.this,"token");
Log.d("token", status);
*/
Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Oops! The Username & Password Do Not Match. Please try again!",
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
if(pd.isShowing()) {pd.dismiss();}
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
//TODO
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
}
else error.printStackTrace();
}
}) {
#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;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
postRequest.setRetryPolicy(new DefaultRetryPolicy(
7000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(postRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
package com.example.mwakidoshi;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by Sly on 2017-11-17.
*/
public class CustomRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = responseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}

Request Https url using Volley

I want to request a webservice with https url, but a Volley Error Occurs (NoConnectionError).
I think the problem is that https url, but I don't found any solution on internet.
Anybody can helps me?
The error is: "com.android.volley.NoConnectionError: java.io.IOException: No authentication challenges found"
Code:
RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();
String url = "https://www.websiteco.com/rest/index.php/login/user/email/ana#gmail.com/password/123456";
JsonObjectRequest json = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String s = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorStr = "";
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
errorStr = "TimeoutError or NoConnectionError";
} else if (error instanceof AuthFailureError) {
errorStr = "AuthFailureError";
} else if (error instanceof ServerError) {
errorStr = "ServerError";
} else if (error instanceof NetworkError) {
errorStr = "NetworkError";
} else if (error instanceof ParseError) {
errorStr = "ParseError";
}
Toast.makeText(getApplicationContext(),errorStr,Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> parms = new HashMap<>();
parms.put("Key-Api", "*******");
return parms;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};
queue.add(json);

Connection Timeout Android

i have an android app in which i hit a web service and gets the result.
Now i want is if result is getting to long to be fetched or in between request internet connection is gone then i show a message or a dialog to the user that Your connection timed out
I've tried this code but this is not working
Any help would be appreciated
blic void getVolleyTask(Context context,
final IVolleyReponse responseContext, String URL) {
RequestQueue request = Volley.newRequestQueue(context);
StringRequest strReq = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response != null) {
JSONArray _array = new JSONArray(response);
responseContext.ResponseOk(_array);
} else {
responseContext.ResponseOk(null);
}
} catch (Exception e) {
e.printStackTrace();
responseContext.ResponseOk(null);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseContext.ErrorBlock();
}
});
strReq.setRetryPolicy(new DefaultRetryPolicy(socketTimeout, maxTries,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.add(strReq);
}
public void getVolleyPostTask(Context context,
final IVolleyJSONReponse jsonResponseContext, String URL,
JSONObject obj) {
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jsonResponseContext.ResponseOk(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
jsonResponseContext.ErrorBlock();
}
}) {
#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;
}
};
myRequest.setRetryPolicy(new DefaultRetryPolicy(socketTimeout,
maxTries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.add(myRequest);
}
thanks in advance!
VollyJson library have a capability to differentiate different network errors while communicating with webservices.When something went wrong with JSONObjectRequest onErrorResponse will be called,there you can differentiate the error as follows.
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//Write Your code here
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}

Categories

Resources