Android Volley - Get response Header AND read html - android

I can't find any solution to this. As of now it seems I have to choose between getting the normal html response or getting only the response headers.
Is there a way to modify my code to get both of these?
Current code (Gives response headers only)
StringRequest stringRequest = new StringRequest(Request.Method.GET, loginURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String responseSession = response.substring(0,response.indexOf(";"));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG ).show();
}
}){
#Override
protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
String sessionId = networkResponse.headers.get("Set-Cookie");
com.android.volley.Response<String> result = com.android.volley.Response.success(sessionId,
HttpHeaderParser.parseCacheHeaders(networkResponse));
return result;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

Use a custom request class for this purpose,
public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {
private Response.Listener<CustomStringRequest.ResponseM> mListener;
public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = responseListener;
}
#Override
protected void deliverResponse(ResponseM response) {
this.mListener.onResponse(response);
}
#Override
protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
ResponseM responseM = new ResponseM();
responseM.headers = response.headers;
responseM.response = parsed;
return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
}
public static class ResponseM {
Map<String, String> headers;
String response;
}
}
And change the code like this ,
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.GET, loginURL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG ).show();
}
}) {
};

Related

POST Request in Volley(using JSON instead of String)

I am developing an app in which i find the origin and destination of a car and send it to a server.
I know how to use volley to send an string however i am finding it hard to send data in JSON format.
Part of the code is given below:
b
tnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
String url = "http://192.168.43.162:8080/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("origin", etOrigin.getText().toString());
params.put("destination", etDestination.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
try this
final String httpUrl = //your url
try {
JSONArray parameters = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(Key,value);
jsonObject.put(Key,value);
parameters.put(jsonObject);
Log.i(TAG,parameters.toString());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
try {
//your code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}
}

Android Volley onResponse get data

In a string post request for logging in. in onResponse all i am returned is the status code of 200. I would like to get the data returned as well. I am not sure where to go from this point forward? Any ideas on how to get the data returned, and not just the status code?
public void requestWithSomeHttpHeaders() {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://......";
JSONObject jsonBody = new JSONObject();
jsonBody.put("username", "yourusername");
jsonBody.put("password", "yourpassword");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
System.out.println(responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Preferably, define a method.
private void doLogin() {
// TODO: startActivity?
}
Then call that
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
doLogin();
}
If you want the data from the server, that is what String response is. Check your Logcat.
As mentioned in the comments, using StringRequest without implementing getBody, parseNetworkResponse, and getBodyContentType might work better.
If you want to parse JSON add method like this
public Profile getUserProfile(String response){
Profile profile = null;
try {
profile = new Profile();
JSONObject jsonObject = new JSONObject(response);
profile.setId(jsonObject.getInt(context.getString(R.string.profile_id)));
profile.setLastName(jsonObject.getString(context.getString(R.string.profile_lastName)));
profile.setName(jsonObject.getString(context.getString(R.string.profile_name)));
profile.setEmail(jsonObject.getString(context.getString(R.string.profile_email)));
} catch (JSONException | NullPointerException e) {
e.printStackTrace();
return null;
}
return profile;
}
In your onResponse method
#Override
public void onResponse(String response) {
//If you have son object
Profile profile = getUserProfile(response)
}

How can I POST a JSONObject using Volley and receive in a String?

I'm trying to post an JSONObject using Volley. Most probably, the servers response is not type JSONObject. Any ideas or workaround?
This is my code:
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonobject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Build.logError("Response:" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Build.logError("Error: " + volleyError);
}
});
requestQueue.add(jsonObjectRequest);
and this is the error response I'm receiving :
com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject
Thank you in advance.
Here's what I did using String request. In this example, I'm posting parameters inside JSON object.
Tested it out using http://posttestserver.com/post.php. Basically override two POST related methods of the super class (Request class) getBody() and getBodyContentType() to supply post data.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
final JSONObject jsonObject = new JSONObject();
jsonObject.put("fName", "First");
jsonObject.put("lName", "Last");
jsonObject.put("age", 11);
jsonObject.put("ts", System.currentTimeMillis());
StringRequest stringRequest = new StringRequest(Request.Method.POST, uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response from server: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (response != null) {
System.out.println("error code: " + response.statusCode);
}
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonObject.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
You have to write custom request.. please try below one
import java.io.UnsupportedEncodingException;
import java.util.Map;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.HttpHeaderParser;
public class ServerStatusRequestObject extends Request<String> {
private final Response.Listener mListener;
private String mBody;
private String mContentType;
private HashMap mCustomHeaders;
public ServerStatusRequestObject(int method, String url,
HashMap customHeaders, String body, Response.Listener listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
mCustomHeaders = customHeaders;
mBody = body;
mListener = listener;
mContentType = "application/json";
if (method == Method.POST) {
RetryPolicy policy = new DefaultRetryPolicy(5000, 0, 5);
setRetryPolicy(policy);
}
}
public ServerStatusRequestObject(String url, HashMap customHeaders,
Response.Listener listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
mCustomHeaders = customHeaders;
mListener = listener;
mContentType = "application/x-www-form-urlencoded";
}
#Override
protected Response parseNetworkResponse(NetworkResponse response) {
String json = null;
try {
json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.success(json,
HttpHeaderParser.parseCacheHeaders(response));
}
#Override
public Map getHeaders() throws AuthFailureError {
if (mCustomHeaders != null) {
return mCustomHeaders;
}
return super.getHeaders();
}
#Override
public byte[] getBody() throws AuthFailureError {
return mBody.getBytes();
}
#Override
public String getBodyContentType() {
return mContentType;
}
public String getContentType() {
return mContentType;
}
public void setContentType(String mContentType) {
this.mContentType = mContentType;
}
#Override
protected void deliverResponse(String arg0) {
// TODO Auto-generated method stub
mListener.onResponse(arg0);
}
}
use like this
ServerStatusRequestObject jsonObjReq = new ServerStatusRequestObject(
Method.POST, Urls.logout, headers, json.toString(),
new Response.Listener<String>() {
#Override
public void onResponse(String arg0) {
// TODO Auto-generated method stub
Common.stopProgressDialog();
System.out.println("string response = " + arg0);
Toast.makeText(MainActivity.this, "Logout success",
Toast.LENGTH_LONG).show();
Common.savePref(MainActivity.this, Constants.sessionId,
null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
Common.stopProgressDialog();
System.out.println("error = " + arg0);
}
});

How to send a POST request using volley with string body?

I'm developing an Android app that communicate with a RESTful web service I wrote. Using Volley for GET methods is awesome and easy, but I can't put my finger on the POST methods.
I want to send a POST request with a String in the body of the request, and retrieve the raw response of the web service (like 200 ok, 500 server error).
All I could find is the StringRequest which doesn't allow to send with data (body), and also it bounds me to receive a parsed String response.
I also came across JsonObjectRequest which accepts data (body) but retrieve a parsed JSONObject response.
I decided to write my own implementation, but I cannot find a way to receive the raw response from the web service. How can I do it?
You can refer to the following code (of course you can customize to get more details of the network response):
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
I liked this one, but it is sending JSON not string as requested in the question, reposting the code here, in case the original github got removed or changed, and this one found to be useful by someone.
public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user",userAccount.getUsername());
params.put("pass",userAccount.getPassword());
params.put("comment", Uri.encode(comment));
params.put("comment_post_ID",String.valueOf(postId));
params.put("blogId",String.valueOf(blogId));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();
JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();
StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Rest response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest response",error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("name","xyz");
return params;
}
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("content-type","application/fesf");
return params;
}
};
requestQueue.add(stringRequest);
I created a function for a Volley Request. You just need to pass the arguments :
public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("username", username);
MyData.put("password", password);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}

error sending data to server using volley library

I have not used volley library much. i have read the tutorials. i want to send data to a url which which will enter that data in database. i have tried the following code but its not working. data is not entered in the database.
String url = "http://tipseducation.com/system/eadmin/insertschedule/";
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Valid Response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("appt_name", ed_name);
params.put("appt_email", ed_email);
params.put("appt_contact", ed_contact);
params.put("appt_date", ed_date);
params.put("appt_time", ed_time);
params.put("appt_service", ed_spinner);
return params;
}
};
can anyone please help me. iam new to this
Instead of getHeaders, you should use getBody for your POST request.
You can refer to my following working sample code (replace my JSONObject and Url by yours). Hope this helps!
...
try {
RequestQueue queue = Volley.newRequestQueue(this);
jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley POST DATA Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/09/17");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
e.printStackTrace();
return null;
}
}
};
queue.addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
...

Categories

Resources