getting empty body while sending post request using volley Android - 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);
}
}

Related

how can send JSON?

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);

My response in Volley request always get into Error Listener

i am using volly for json response this is my java code i tried every thing but unable to find error in it. it always go to Error Listener.i really dont know why my response goes to error listener any body help me please thanks in advance
private void userLoign() {
name = Name_Et.getText().toString();
email = Email_Et.getText().toString();
password = Password_Et.getText().toString();
Toast.makeText(MainActivity.this, "enter in userlogin", Toast.LENGTH_SHORT).show();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String URL = "added-platters.000webhostapp.com/application/index.php";
Toast.makeText(MainActivity.this, "enter in Volley", Toast.LENGTH_SHORT).show();
StringRequest myReq = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("value");
Log.e("value in success", String.valueOf(success));
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.i("myTag", e.toString());
Toast.makeText(MainActivity.this, "Parsing error", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("myTag", error.toString());
Toast.makeText(MainActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "Register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("lat", "1234");
params.put("log", "1234");
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myReq.setShouldCache(false);
queue.add(myReq);
}
and this is my json response in php
{"value":"Record Inserted Successfully"}
The Problem is URL Protocol not specified
String URL = "added-platters.000webhostapp.com/application/index.php";
to
String URL = "http://added-platters.000webhostapp.com/application/index.php";

Android Volley post request not working on click?

Im creating an application where i can make reports and,on button click nothing happens,even the response does not come,toast not showing up. This volley post i have used it before and it is correct,another thing i should write is that i have to send the token for authorization.
this is my code:
//this is button click
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
volley_send();
}
});
//-----------------------------------------------------
//this is volley post
private void volley_send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, "my_url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// save_on_sharedPreference("email",email);
if(!response.isEmpty()){
try {
JSONObject jsonObject = new JSONObject(response);
error = jsonObject.getBoolean("error");
String message = jsonObject.getString("message");
if(!error){
//String token = jsonObject.getString("token");
//JSONObject data = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Raport_Cat_NoPhoto.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
// JSONArray feedArray = response.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
System.out.println("JSONException :"+e.toString() );
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),getString(R.string.err_connection),Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
//TODO
//Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_authentication),Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
//TODO
//Toast.makeText(getApplicationContext(),"3",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_system),Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
//TODO
//Toast.makeText(getApplicationContext(),"4",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_network),Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
//TODO
//Toast.makeText(getApplicationContext(),"5",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_processing),Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Bearer "+ApiKey);
return headers;
}
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("category","cat_ankese");
params.put("description",description.getText().toString());
params.put("city",Qyteti);
params.put("fshati",fshati.getText().toString());
params.put("address",address.getText().toString());
params.put("additional_information1",personidyshuar.getText().toString());
params.put("name",emer.getText().toString());
params.put("surname",mbiemer.getText().toString());
params.put("telephone",telefon.getText().toString());
params.put("email",email.getText().toString());
params.put("info_latt",my_latitude);
params.put("info_long",my_longitude);
params.put("file[]",image123);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
I don't know what it is wrong...
Sems like the problem was with the Authorization header,for any reason it requires only one parameter. Thank you all for replies!

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
}

Send post data to server using Volley android

I am trying to send some data to the server using the Volley library.
private void registerUser(final String email, final String username,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
// String status = jObj.getString("status");
// User successfully stored in MySQL
// Now store the user in sqlite
String name = jObj.getString("username");
String email = jObj.getString("email");
String password = jObj.getString("password");
// String created_at = user
//.getString("created_at");
// Inserting row in users table
// db.addUser(name, email);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("username", username);
params.put("password", password);
return params;
}
Unfortunately no json is sent and I get nothing back. Here is a sample of my logcat output. After sending a request successfully to the server, I want to get response with success/fail.
Register Response: ---- YOUR DATA ----
username=xxx&email=xxx%40gmail.com&password=xxxx&-------------------
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ org.json.JSONException: Value ---- of type java.lang.String
cannot be converted to JSONObject
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
Any help please? Thanx.
private void postUsingVolley() {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
final String mVendorId = DeviceDetails.getInstance(mContext).getVendor_id();
String mUserId = UserModel.getInstance(mContext).getUser_id();
final HashMap<String, String> postParams = new HashMap<String, String>();
sendFeedbackParams.put("key1", value1);
sendFeedbackParams.put("key2", value2);
sendFeedbackParams.put("key3", value3);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
ApplicationData.POST_URL, new JSONObject(postParams),
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("TAG", response.toString());
try {
//Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "Thank you for your post", Toast.LENGTH_LONG).show();
if (response.getBoolean("status")) {
pDialog.dismiss();
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
pDialog.dismiss();
if (isNetworkProblem(error)) {
Toast.makeText(mContext, "Internet Problem", Toast.LENGTH_SHORT).show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getRequestHeaders();
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(8000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Use Volley like this,... It is working for me.
First of all you are not sending json to your server. You are sending parametrized url with post method and getting json text as response.
I think the problem is the response from the server which is supposedly json. But from your log, this text "---- YOUR DATA ----" which you get from Log.d(TAG, "Register Response: " + response.toString()); is not at all json formatted . So you need to modify your server to respond in correct json format.
This is the solution. I had to use the JsonObjectRequest class and not the StringRequest on. What JsonRequest does is that it converts your HashMap key-value pairs into a JSON Format.
private void registerUser(String email_address,String username, String
password) {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
final String mVendorId =
DeviceDetails.getInstance(mContext).getVendor_id();
String mUserId = UserModel.getInstance(mContext).getUser_id();
String location = getResources().getConfiguration().locale.getCountry();
final HashMap<String, String> postParams = new HashMap<String, String>
();
postParams.put("username", username);
postParams.put("email", email_address);
postParams.put("password", password);
postParams.put("location", location);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(AppConfig.URL_REGISTER, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("TAG", response.toString());
try {
Toast.makeText(getApplicationContext(),
response.getString("message"), Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Thank
you for your post", Toast.LENGTH_LONG).show();
if (response.getString("status").equals("success")){
session.setLogin(true);
pDialog.dismiss();
Intent i = new
Intent(RegisterActivity.this,Welcome.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
JSon post
public void makePostUsingVolley()
{
session = new SessionManager(getActivity().getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
final String token = user.get(SessionManager.KEY_NAME);
//Toast.makeText(getActivity().getApplicationContext(),name, Toast.LENGTH_SHORT).show();
final Map<String, String> params = new HashMap<String, String>();
//params.put("Employees",name);
String tag_json_obj = "json_obj_req";
String url = "enter your url";
final ProgressDialog pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest req = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
// final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
//"http://emservices.azurewebsites.net/Employee.asmx/CheckUserGet", new Response.Listener<JSONObject>() {
#Override
public void onResponse(String response) {
JSONObject json;
// Toast.makeText(getActivity().getApplicationContext(),"dfgghfhfgjhgjghjuhj", Toast.LENGTH_SHORT).show();
//Toast.makeText(getActivity().getApplicationContext(),obb.length(), Toast.LENGTH_SHORT).show();
// JSONObject data=obj.getJSONObject("Employee_Name");
ObjectOutput out = null;
try {
json = new JSONObject(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.hide();
// Toast.makeText(getApplicationContext(),"hi", Toast.LENGTH_SHORT).show();
Log.d("", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
pDialog.hide();
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username",name);
params.put("password",password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_obj);
}
requestQueue= Volley.newRequestQueue(MainActivity.this);
StringRequest request=new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
Log.d("response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name.getText().toString().trim());
jsonObject.put("email", email.getText().toString().trim());
jsonObject.put("phone", phone.getText().toString().trim());
} catch (JSONException e) {
e.printStackTrace();
}
Map<String, String> params = new HashMap<String, String>();
params.put("message", jsonObject.toString());
return params;
}
};
requestQueue.add(request);
[["deep","dee#gmail.com","8888999999"]]

Categories

Resources