I want to post an int to an https address and pass 3 JSON objects to text views and I can't get JSON results. I've tried to use methods in onResponse but it's not working. How can I POST an integer and parse some JSON objects to text views? I'm a beginner in Android developing and I don't know how to resolve this problem.
What's the problem? please help
if(isNetworkAvailable()){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://example.com/api";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response);
} catch (JSONException e) {
e.printStackTrace();
alertUserAboutError();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
mStoreName.setText("Error");
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("category_id", "28");
return params;
}
};
queue.add(postRequest);
}
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show(); }
private void updateDisplay() {
mStoreName.setText(mStoreDetails.getStoreName());
mInstagram.setText(mStoreDetails.getInstagram());
mTelegram.setText(mStoreDetails.getTelegram());
}
private StoreDetails getStoreDetails(String jsonData) throws JSONException {
JSONObject JSONRequest = new JSONObject(jsonData);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setStoreName(JSONRequest.getString("store_name"));
storeDetails.setInstagram(JSONRequest.getString("instagram"));
storeDetails.setTelegram(JSONRequest.getString("telegram"));
return storeDetails;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
This works for me. Use an stringrequest to put the post data to the request. After onResponse was called I create an JSON-Object from the string:
public void doServerRequest(final Context context, final String url, final Map<String,String> postParameters, final HashMap<String,String> getParameters, final OnFinishTaskListener<String, JSONObject> listener){
Log.d(TAG,"Start new server request (" + url + ")");
StringRequest request = new StringRequest(Request.Method.POST, addParametersToUrl(url, getParameters), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
try {
JSONObject json = new JSONObject(response);
if (json.getInt(CODE_TAG) == 0){
listener.getResult(SUCCESS_TAG, json);
} else {
listener.getResult(ERROR_TAG, null);
}
} catch (Exception e){
e.printStackTrace();
listener.getResult(ERROR_TAG, null);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
listener.getResult(ERROR_TAG, null);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
if(postParameters == null){
return new HashMap<String, String>();
}
return postParameters;
}
};
requestQueue.add(request);
}
This adds the get-Paramters to the URL (if exist):
private String addParametersToUrl(String url, HashMap<String,String> getParameters){
if(getParameters == null || getParameters.size() == 0){
return url;
}
Log.d(TAG,"Preparing URL: "+url);
StringBuilder stringBuilder = new StringBuilder(url);
stringBuilder.append("?");
int i = 0;
for (String key : getParameters.keySet()) {
if(i>0) stringBuilder.append("&");
stringBuilder.append(key).append("=").append(getParameters.get(key));
i++;
}
url = stringBuilder.toString();
Log.d(TAG,"Prepared URL: "+url);
return url;
}
I use this listener interface:
public interface OnFinishTaskListener<S,J> {
public void getResult(S string, J json);
}
Related
I have an array which is contain image quantity for image and another is image size array which is contain image size, also an image array. I'm trying to send them to server but i failed every time. I'm trying many example but nothing was worked for me. Is there any other way to do this ? Please give me some hints or link.
how to send array of params using volley in android
public void uploadMultipleImage(String url, final List<SelectedImageModel> selectedImageModels)
{
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
responseListener.onResultSuccess(resultResponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String result = new String(networkResponse.data);
responseListener.onResultSuccess(result);
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("size["+i+"]",selectedImageModels.get(i).getPhotoSize());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("quantity["+i+"]",selectedImageModels.get(i).getPhotoQuantity());
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer "+requiredInfo.getAccessToken());
headers.put("Accept", "application/json");
headers.put("Content-Type", "x-www-form-urlencoded");
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("image["+i+"]",new DataPart("imageName",UserProfile.getFileDataFromDrawable(selectedImageModels.get(i).getPhoto())));
return params;
}
};
requestQueue.add(multipartRequest);
}
Every time i'm getting com.android.volley.server error 500 this error
Make a method for send array of params.
private String makeJsonObjectParams() {
//In mediaData,I am sending image to AWS and I will get the download link and I
// am storing the downloadurl in downloadurl arrayslist.
JSONArray mediaData = new JSONArray();
try {
if(img1 != 1) {
JSONObject temp = new JSONObject();
temp.put("file", download_url.get(0));
temp.put("type", "signature");
mediaData.put(temp);
}
if(img2 != 1){
JSONObject temp1 = new JSONObject();
temp1.put("file", download_url.get(1));
temp1.put("type", "id proof");
mediaData.put(temp1);
}
} catch (JSONException e) {
e.printStackTrace();
}
//for sending normal details like text
JSONObject updateDetails = new JSONObject();
try {
updateDetails.put("status", 2);
updateDetails.put("userId", sharedPreferences.getString("user_ID",""));
updateDetails.put("deviceToken", splash_screen.android_id);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonVerificationDetails = new JSONObject();
try {
jsonVerificationDetails.put("type", verificatin_type);
jsonVerificationDetails.put("durationOfStay", durationOfStay.getText().toString());
jsonVerificationDetails.put("media", mediaData);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("verificationDetails", jsonVerificationDetails);
jsonBody.put("updateDetails", updateDetails);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonBody.toString();
return mRequestBody;
}
}
Through the below code send the code to server.
void submitData(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
final String mRequestBody = makeJsonObjectParams();
StringRequest stringRequest = new StringRequest(Request.Method.POST, completedTaskUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//do whatever you want
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#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);
}
// return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
return super.parseNetworkResponse(response);
}
};
requestQueue=Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
} catch (Exception e) {//JSONException e
e.printStackTrace();
}
}
This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#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;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...
So, i have this code to make a POST request with volley:
public class MainActivity extends AppCompatActivity {
Button btnSearch;
ProgressDialog loadingDialog;
ListView lvResult;
String session_id;
RequestQueue queue;
MyCookieManager myCookieManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch = (Button) findViewById(R.id.btnSearch);
lvResult = (ListView) findViewById(R.id.lvResult);
loadingDialog = new ProgressDialog(MainActivity.this);
loadingDialog.setMessage("Wait.\nLoading...");
loadingDialog.setCancelable(false);
myCookieManager = new MyCookieManager();
requestCookie(); //FIRST CALL TO GET SESSION ID
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showLoading();
requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
}
});
}
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
//
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO¶m2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap < String, String > ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
//"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
return params;
}
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(postRequest);
}
public void requestWithSomeHttpHeaders() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
Log.d("Response", response);
String x = myCookieManager.getCookieValue();
String status = "";
try {
JSONObject resultObject = new JSONObject(response);
Log.d("JSON RESULT =>", resultObject.toString());
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
hideLoading();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO¶m2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map <String, String> getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap <String, String> ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
return params;
}
};
queue.add(postRequest);
}
private void showLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!loadingDialog.isShowing())
loadingDialog.show();
}
});
}
private void hideLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
});
}
}
If I send a valid cookie ID this return a valid JSON object else a empty object.
I tried (unsuccessfully) to set default cookie handles like
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
but I get a empty object.
How to put a valid cookie session ID to post request?
So the problem was getting a valid cookie. My mistake was to get it from the POST request itself. I kept the same working principle, getting the cookie when I started the application but using GET instead of POST and calling the root of the URL instead of the address where I get the JSON.
My solution looked like this:
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(getRequest);
}
Using cookies with Android volley library
Request class:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* #param method
* #param url
* #param params
* A {#link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* #param listener
* #param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
#Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* #see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* #see com.android.volley.Request#getHeaders()
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
MyApp:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
#Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* #param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.
for getting cookie from login request
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
CookieManager cookieManage = new CookieManager();
CookieHandler.setDefault(cookieManage);
progressDialog.hide();
try {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
Log.e("session", sessionId);
Log.e("responseString", responseString);
JSONObject object = new JSONObject(responseString);
CustomStringRequest class
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 {
public Map<String, String> headers;
public String response;
}
}
set cookie when add request to server..
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String session=sharedPreferences.getString("sessionId","");
headers.put("Cookie",session);
return headers;
}
I made a project and using REST to send and get data from server, I used HttpURLConnection to send request
then I've found volley that make it easier to use, but I have a problem using cookies on volley
here is my request function
public void doActionJsonPost() {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, IConstants.BASE_URL + url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(response);
String msgCode = jsonObject.getString("responseCode");
} catch (JSONException e) {
LoggingHelper.verbose(e.toString());
iHttpAsync.onAsyncFailed(e.toString());
} catch (Exception e) {
LoggingHelper.verbose(e.toString());
iHttpAsync.onAsyncFailed(e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
LoggingHelper.verbose("ERROR");
iHttpAsync.onAsyncFailed(error.getMessage());
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
iHttpAsync.onAsyncProgress();
return parameters.getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getAuthHeader(context);
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Map<String, String> responseHeaders = response.headers;
String rawCookies = responseHeaders.get("Set-Cookie");
return super.parseNetworkResponse(response);
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
I have override parseNetworkResponse to get headerResponse, but I cannot see cookies there
my question is, how can I send and get cookies from volley?
try this and pass your header in this methods
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
I have a big problem with volley request sequence and making json array out of first request response for second request.
this is the code :
JSONObject imageAddedResponse = new JSONObject();
JSONArray imagesAddedResponse = new JSONArray();
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
first request post to CMS and get some information for images posted and then I need to add those information to next post to make entity based on response I got back from first post request.
int totalSuccesfulImagePost = 0; //this variable increment when each succesful response from multipart-request
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages.getJSONObject(0));
totalSuccesfulImagePost++; //here we increase the count
postRequest(token); //call this method and check wheather all the image uploaded or not
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
}
//make this as seperate method and call when all multipart-request call succesful
public void postRequest(String token){
if(totalSuccesfulImagePost != mImages.size()) {
//this means not all the images posted yet, hence return the method
return;
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();.getJSONObject(0)
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
updated your code. Hope this may help you.
I've created new method for JsonObjectRequest with the name postRequest();
totalSuccesfulImagePost variable holds the no. of succesfull response for image upload
new method postRequest() calls at each multipart-request response
postRequest() methods check if not all response process yet than skip the 2nd api call
Also see how fb do this batch request https://developers.facebook.com/docs/android/graph/ -> Batch Reqest
Note -
Ive increment the variable totalSuccesfulImagePost and handle in each response, although you need to Response.ErrorListener()
Although you can go with the ThreadPoolExecutor option where each thread is created to handle each multipart-request upload and after all thread execution , call the method postRequest()
Work-around using ThreadPoolExecutor
a) Create ThreadPoolExecutor & initialize min/max pool size
b) Asign each mulitpart-request to upload image to each thread
c) Add all thread (contain image upload multipart-request) to ThreadPoolExecutor
d) Execute pool
e) call postRequest() method when ThreadPoolExecutor is empty i.e. this means all the thread execution is done and ready to call postRequest()
it is possible using Priority Of each Request.
private Priority priority = Priority.HIGH;
StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#Override
public Priority getPriority() {
return priority;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);