I am using Post Method to send data to server and the data includes strings and images values images value are send through multipart now i am getting some error to reslove i want to post all my data in Log to see where the data is not able to send can any one help me out to use log for all the paremeters values include image string values in log
Post Method Sample
private void new_processing() {
String URL = "Url";
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Log.d("response", new String(response.data));
rQueue.getCache().clear();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
if (action_taken == "Sample Taken " ||action_taken.equals("Sample Taken ")) {
JSONObject json2 = new JSONObject();
try {
json2.put("sampletype", product_type);
json2.put("samplecode", sample_code);
} catch (JSONException e) {
e.printStackTrace();
}
JsonArray sample_obj = new JsonArray();
sample_obj.add(String.valueOf(json2));
params.put("Raid_Sample", sample_obj.toString());
params.put("Raid_Action", null);
} else if (action_taken.equals("Sale Stoped") || action_taken.equals("Licence Cancelled") ||action_taken == ("Licence Cancelled") || action_taken.equals("Licence Suspended")) {
JSONObject json2 = new JSONObject();
try {
json2.put("actiontype", action_taken);
json2.put("actiondate", lic_date);
json2.put("letterno", lic_letter);
json2.put("copyno", lic_copy);
} catch (JSONException e) {
e.printStackTrace();
}
params.put("Raid_Action", String.valueOf(json2));
params.put("letterfile", image_letter);
Log.i("action_object", String.valueOf(json2));
}
params.put("AuthID", AuthId);
params.put("producttype", product_type);
/* params.put("raidother", raid_type_other);
params.put("violationother", voilation_other);*/
params.put("dateofraid", raid_date);
params.put("locationname", location_name);
params.put("locationaddress", location_address);
JSONArray array;
array = new JSONArray();
for (int i = 0; i < movieList1.size(); i++) {
JSONObject movieObject = new JSONObject();
try {
movieObject.put("name", movieList1.get(i).getName());
movieObject.put("designation", movieList1.get(i).getDesignation());
movieObject.put("postingplace", movieList1.get(i).getPostingplace());
array.put(movieObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
memberlist = String.valueOf(array);
Log.i("arraylist", memberlist.toString());
params.put("Raid_Team", memberlist);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("picurl1", new DataPart(imagename + ".jpge", getFileDataFromDrawable(bitmap)));
return params;
}
};
volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rQueue = Volley.newRequestQueue(ScrollingActivity.this);
rQueue.add(volleyMultipartRequest);
}
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();
}
}
I want to pass {"data:"[{"id":"12"}]} in volley request body.
private void reqrej(final String currentLat) {
String insertData = "http://www.xxxxxxxx.com/makeinforequest.php";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, insertData, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("json", response.toString());
tv.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// String mylong = String.valueOf(mCurrentLocation.getLongitude()).toString();
Map<String, String> params = new HashMap<String, String>();
params.put("data", "");
//where I can type request code?
return checkParams(params);
}
private Map<String, String> checkParams(Map<String, String> map) {
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
if (pairs.getValue() == null) {
map.put(pairs.getKey(), "");
}
}
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
please guide me how to pass this things in android with volley , i try so many times but not success.
Try This
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
try {
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
JSONObject idJson=new JSONObject();
idJson.put("id","12");
jsonArray.put(jsonObject);
jsonObject.put("data",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonObject.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", 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);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Try this
try
{
JSONObject obj = new JSONObject();
JSONArray jsonArray = new JSONArray();
obj.put("id", "12");
jsonArray.put(obj);
JSONObject jsonObjectdata = new JSONObject();
jsonObjectdata.put("data", jsonArray);
Log.i("Json Response",""+ jsonObjectdata.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use JsonObjectRequest
Here is the example you can try https://stackoverflow.com/a/28344904/6676466
in this example there is pass your jsonString inside new JSONObject(postParam).
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);
Here is my code :
{
"VisitorDetails":[
{
"Name":"Ramesh",
"Gender":"Male",
"Age":24,
"MobileNo":9502230173,
"LandLine":"040140088",
"EmailId":"rameshkandula24#gmail.com",
"CreatedOn":"08-25-2016",
"Address":"Hyderabad",
"Profession":"Software",
"FamilyMembers":5,
"HomeTown":"Gannavaram",
"MedicalHealing":"Noooooo",
"Isinterestedwithcompanies":1,
"IsBetterlivingStandards":1,
"IsInterestedinConference":1,
"VisitorExcites":[1,2,3]
"jsonkey" : "rUinterested"
}
]
}
try {
JSONArray arry = new JSONArray();
JSONObject iner = new JSONObject();
iner.put("Name", "nmae");
//all detail to iner
arry.put(iner);
JSONObject outer = new JSONObject();
outer.put("VisitorDetails", arry);
}
catch (Exception e){
}
final JSONObject jsonObject=new JSONObject();
try {
JSONArray jsonArray=new JSONArray();
JSONObject innerobject=new JSONObject();
innerobject.put("Name",Name);
innerobject.put("Address",Country);
jsonArray.put(innerobject);
jsonObject.put("VisitorDetails",jsonArray);
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL,jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
Toast.makeText(MainActivity.this, "your data successfully register", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
Toast.makeText(MainActivity.this, "your data not register", Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> param = new HashMap<String, String>();
param.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return param;
}
};
Update : add this in your gradle(app level)
compile 'com.android.volley:volley:1.0.0'
developing from Bansal ans .
your json data
JSONArray arry = new JSONArray();
try {
JSONObject jsonobject_one = new JSONObject();
jsonobject_one.put("Name", "Name");
// add all details like this
arry.put(jsonobject_one);
JSONObject jsonobject_TWO = new JSONObject();
jsonobject_TWO.put("VisitorDetails", arry);
}catch (JSONException e) {
e.printStackTrace();
}
Then Your jsonRequest
JsonArrayRequest jsonArryReq = new JsonArrayRequest(
Request.Method.POST,url, arry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
protected Map<String, String> getParams()
{
Map<String, String> param = new HashMap<String, String>();
if (!GetMethod) {
param.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return param;
}
return param;
}
This is the code i use:
if (toEditText.getText().toString().length() > 0) {
getName = toEditText.getText().toString().substring(0, toEditText.getText().toString().length() - 1) + "";
StringBuffer sb = new StringBuffer();
sb.append(Constants.SERVER_IP);
sb.append("/api/groups.json");
String url = sb.toString();
LogService.log(TAG, "download url: " + url);
JSONObject juser = new JSONObject();
JSONArray userIds = new JSONArray();
for (int i = 0; i < user_ids.size(); i++) {
userIds.put(user_ids.get(i));
}
try {
juser.put("group_name", getName);
juser.put("owner_id", UserCredentialsPersistence.getUserId(context));
juser.put("user_ids", userIds);
juser.put("group_type", null);
juser.put("name_protected", true);
LogService.log(TAG, "JSON: " + juser.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "%%%%%Response:" + response.toString());
int group_id = 0;
group_name = "";
if (response != null) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject userObj2 = (JSONObject) response.get("group");
group_id = userObj2.getInt("id");
group_name = userObj2.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
LogService.log(TAG, "id: " + group_id);
LogService.log(TAG, "name: " + group_name);
getName = "";
toEditText.setText("");
GroupAndConversationManager.getInstance(context).addNewConversation(group_id, group_name);
hideSearchFild();
int curr_group_id = UserCredentialsPersistence.getCurrentGroupId(context);
changeGroup(curr_group_id, group_id);
showGroupToast(group_name);
setVideoPlayback();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, error.getMessage());
}
}) {
#Override
public HashMap<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
StringBuilder builder = new StringBuilder();
builder.append(UserCredentialsPersistence.restoreCookie(context));
params.put("Cookie", builder.toString());
return params;
}
};
mRequestQueue.add(jr);
}
Now, Logcat gives me back this line:
07-12 11:21:53.702: I/VideoPlayerFragment(27428): java.io.IOException: No authentication challenges found
I have also tried to override getHeaders, instead of getParams(), but i get an error, so the webservice does not work correctly. This is from where I've got the ideea to override getParams/getHeaders: How to set custom header in Volley Request
Could anyone explain to me what I'm doing wrong?
using this override resolved it:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", UserCredentialsPersistence.restoreCookie(context).toString());
return headers;
}