Volley Request not giving any reponse - java

I am new to Android. I am figuring out how to make network calls. I am trying to send Headers along with JSON data. I tried debugging the code but it's not going to onResponse(). Can someone tell me what am i doing wrong .
Below is my code.
String url = "https://api.....";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("image", "https://i.imgur.com/5KdM.jpg");
jsonObject.put("subject_id", "Elixabeth");
jsonObject.put("gallery_name", "MyGallery");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null){
}
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("app_id", "");
headers.put("app_key", "");
headers.put("Content-Length", "124");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
I tried the same in Postman with same data and I am getting response.

Put the log inside
onResponse(JSONObject response) method Log.d("Response", response.toString()); and in
onErrorResponse(VolleyError error) method Log.e("Error", error.getMessage());.
Then check the logcat,you can find what goes wrong...

Related

Android volley returns clienterror 400 [Bad request]

I try everything to solve it but I couldn't. can anybody help me to solve this.
I try to login through volley but it gives bad request 400 error, I think it is because of body content type but I also override getbodycontenttype method but it doesn't work,
here is code
String url = "http://192.168.1.129:5000/api/dealers/login";
StringRequest stringRequest = new StringRequest( Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
Log.d("response", response);
try {
JSONObject data= new JSONObject(response);
//Boolean error =jsonObject.getBoolean("error");
if (data.getString("success").equals("true")) {
String message=data.getString("msg");
startActivity( new Intent( LoginActivity.this, MainActivity.class ) );
finishAffinity();
} else {
Toast.makeText(LoginActivity.this,
data.getString("msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(LoginActivity.this, String.valueOf(networkResponse.statusCode),
Toast.LENGTH_SHORT).show();
}else{
Log.e("Status code", String.valueOf(error));
Toast.makeText(LoginActivity.this, String.valueOf(error),
Toast.LENGTH_LONG).show();
}
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("mobile",userMobile);
params.put("password",userPassword);
return params;
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(stringRequest);
HelloIf your server is correct, do this, but when I used this address, I did not receive any data ...
I also made a error in doing a project using it ... it is better to use version of 1.1.0 and before it ...

Error in Json in volley to Android Studio

I want to call a Api But Reception error is running !!
I have a Json api
A Java class to call
Please help me fix the error!
my jeson:
my class in load data:
public void loadproductview() {
String url = "https://alphaonline.ir/index.php?route=api32/product/product&token=3344556677";
Response.Listener<JSONObject> objectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
txt_name.setText(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
};
Map<String, String> params = new HashMap();
params.put("product_id", "237");
JSONObject parameters = new JSONObject(params);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, parameters, objectListener, errorListener);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
}
You are initializing JSONObject with Map which is wrong>
Directly put the values in JSONObject.
JSONObject parameters = new JSONObject();
parameters.put("product_id", "237");
Try this:-
public void loadproductview() {
String url = "https://alphaonline.ir/index.php?route=api32/product/product&token=3344556677";
Response.Listener<JSONObject> objectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
txt_name.setText(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductActivity.this, error.toString(),
Toast.LENGTH_SHORT).show();
}
};
JSONObject parameters = new JSONObject(params);
parameters.put("product_id", "237");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
parameters, objectListener, errorListener);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
}
I am not sure how you handle the singleton instance of the request, so instead of this:
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
do this:
RequestQueue queue = Volley.newRequestQueue(this);
queue.addToRequestQueue(request);

Notifications are not send while I'm receiving no error

I'm creating a application but I'm stuck on the notification part. I want the android app to send a notification when I press on the button. I've done that by using HTTP request to Firebase but it is not sending the notification. It also does not give me a error. I followed a YouTube tutorial online but I couldn't contact the creator of the video and nobody in the comments section could help me.
private RequestQueue mRequestQueue;
private String URL = "https://fcm.googleapis.com/fcm/send";
public void sendMessage() {
JSONObject mainObj = new JSONObject();
try {
mainObj.put("to:", "/topics/news");
JSONObject notificationObj = new JSONObject();
notificationObj.put("title", "any title");
notificationObj.put("body", "any body");
mainObj.put("notification",notificationObj);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
mainObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(Main3Activity.this, "LADIES AND GENELTJEATMK", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main3Activity.this, "ERROR E SAH", Toast.LENGTH_SHORT).show();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Content-Type", "text/json");
header.put("authorization", "key=MYKEYSHOULDCOMEHERE");
return header;
}
};
mRequestQueue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
}

How to fix "Volley: [15771] BasicNetwork.performRequest: Unexpected response code 404 in android?

The API is developed in Wordpress with POST method. API is working fine in POSTMAN and iOS(swift). I am getting response in POSTMAN and my colleague iOS developer also getting response.
But in Android I am getting 404 error in Android Studio.
I am trying to resolve with different Volley request like StringRequest, JSONObjectRequest and HttpURLConnection with AsyncTask. But getting only 404 error. Any one tell me what is the exact issue?
Below is my code.
private void RegisterUser(){
final ProgressDialog progressDialog = new ProgressDialog(RegistrationActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait...");
progressDialog.show();
StringRequest postrequest = new StringRequest(Request.Method.POST, Urls.REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
Log.e("res","==> "+response);
}
catch (Exception e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {progressDialog.dismiss();error.getLocalizedMessage();}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "khushbu");
params.put("email", "kh#test.com");
params.put("user_pass", "test#123");
params.put("display_name", "khushbu");
params.put("company_name", "");
params.put("nature_of_business", "");
params.put("country", "");
params.put("nonce", "12e099a946");
params.put("notify", "both");
params.put("insecure", "cool");
Log.e("params","==> " + params);
return params;
}
};
FlawlessApplication.getInstance().addToRequestQueue(postrequest);
}
I also tried with adding headers but can't get any solution.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
params.put("cache-control", "no-cache");
return params;
}
Thank you in advance.
final ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(mContext, "", "Loading..");
progressDialog.setCancelable(false);
progressDialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
HashMap<String, String> params = new HashMap<>();
params.put("username", "khushbu");
params.put("email", "kh#test.com");
params.put("user_pass", "test#123");
params.put("display_name", "khushbu");
params.put("company_name", "");
params.put("nature_of_business", "");
params.put("country", "");
params.put("nonce", "12e099a946");
params.put("notify", "both");
params.put("insecure", "cool");
Log.e("params","==> " + params);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
Urls.REGISTER,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.e("res","==> "+response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Do something when error occurred
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headerParams = new HashMap<>();
//add header params if having
headerParams.put("KEY", "value");
return headerParams;
}
};
// Add JsonObjectRequest to the RequestQueue
requestQueue.add(jsonObjectRequest);
In my case.
I was using the http in my API so after changing to https it worked for me. and in postman no matter it http or https it works the same.

How to send request Header is "Content-Type":"application/json" when GET on Volley

I try to use GET on Volley , but i need send request to application/json .
I take a look for some answers , i try to use jsonBody , but it shows error:
null com.android.volley.ServerError
Here is my code:
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
JSONObject jsonBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
} catch (JSONException ex) {
ex.printStackTrace();
}
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(jsonObjectRequest);
}
}
Is any one can teach me how to fix this , any help would be appreciated.
Here is my url:
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
Implementation in your's
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { //no semicolon or coma
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
}
In general for setting a custom header you need to override getHeaders and set the custom header manually. However, volley handles content type headers differently and getHeaders way does not always work.
So for your case you need to override getBodyContentType. So your code will look like
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}){
#Override
public String getBodyContentType(){
return "application/json";
}
};
I try to use GET on Volley
The docs for the method you are calling says this
Constructor which defaults to GET if jsonRequest is null, POST otherwise
You can't GET with an HTTP JSON body. Maybe that's the error.
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
That's not the header, so pass in null here to do GET
new JsonObjectRequest(url, null,
And towards the end of your request, override a method to request JSON
...
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { // Notice no semi-colon here
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
Use String request instead of jsonrequest like this
StringRequest loginMe = new StringRequest(Request.Method.GET, "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("LoginActivity -- onResponse --> " + response);
if (progressDialog != null) {
progressDialog.dismiss();
}
try {
JSONObject jsonObject = new JSONObject(response);
} catch (Exception e) {
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onResponse-- Exception --> ".concat(e.getMessage()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null) {
progressDialog.dismiss();
}
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onErrorResponse --> ".concat(error.getMessage()));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
System.out.println("LoginActivity -- LoginParams --> " + params.toString());
return params;
}
};
loginMe.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(loginMe);

Categories