Post JsonObject use Volley - android

I am using HttpPost to post data to a backend server, and it work well with this code below :
public void postData() {
String url = Configs.URL_OWS;
String odmName = Configs.ODM;
String keymd5 = getKeyMD5();
JSONObject jsonObject = new JSONObject();
jsonObject.put("model", model);
jsonObject.put("imei", imei1);
jsonObject.put("imei2", imei2);
jsonObject.put("build", buildVersion);
if (CommonUtils.isNetworkConnected(mContext)) {
// Create a new HttpClient and Post Header
Handler handler = new Handler(Looper.getMainLooper());
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, Configs.TIME_OUT);
HttpConnectionParams.setSoTimeout(myParams, Configs.TIME_OUT);
HttpClient httpclient = new DefaultHttpClient(myParams);
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
httppost.addHeader("Authorization", odmName + ":" + keymd5);
// httppost.addHeader("POST", "/api/ows HTTP/1.1");
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
JSONObject jsonResponse = new JSONObject(result);
String status = jsonResponse.optString("status");
if (status.equals(Configs.RESPONSE_OK)) { // response 200, send successfull
Log.i(Configs.APP_NAME + " " + TAG, "Send data successful");
} else {
Log.i(Configs.APP_NAME + " " + TAG, "Send data failed:");
}
} catch (final ClientProtocolException e) {
Log.i(Configs.APP_NAME + " " + TAG, "ClientProtocolException " + e.getMessage());
} catch (final IOException e) {
Log.i(Configs.APP_NAME + " " + TAG, "IOException " + e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i(Configs.APP_NAME + " " + TAG, "Network not connected ");
}
}
I switched to use Volley instead HttpPost but server always return error , the code for Volley method :
public void postDataByVolley() {
String url = Configs.URL_OWS;
String odmName = Configs.ODM;
final String keymd5 = getKeyMD5();
HashMap<String, String> params = new HashMap<String, String>();
params.put("model", model);
params.put("imei", imei1);
params.put("imei2", imei2);
params.put("build", buildVersion);
if (CommonUtils.isNetworkConnected(mContext)) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(Configs.APP_NAME + " " + TAG, "Success ");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(Configs.APP_NAME + " " + TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-type", "application/json");
headers.put("Authorization", odmName + ":" + keymd5);
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(Configs.TIME_OUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(jsonObjectRequest);
}
}
I can not find where I was wrong with the code for Volley method. Is there any problem in my Volley method?

It is difficult to say why you are facing an error .please check that url and parameters are sent correctly .once you get the error then paste error log here
Check the following link to understand it better
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Related

PUT Request for Json with Json array inside

I'm trying to update a PUT request which has a JSONArray inside it and I'm constantly getting a 500 error response. Here how the api structure is:
{
"imei": 514515854152463,
"franquia": "SAO",
"sistema": "PEGASUS",
"lista": 2055313,
"entregas":[
{
"codHawb": "02305767706",
"dataHoraBaixa": "2020-12-03T15:26:22",
"foraAlvo": 1000,
"latitude": 44.4545,
"longitude": 45.545,
"nivelBateria": 98,
"tipoBaixa": "ENTREGA"
}
]
}
I've tried the api in Postman to see if its working and it is. But when I'm trying it in the program using Volley I'm getting that error. I've tried volley and here is the code:
private void PutJsonRequest() {
try {
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("imei", "514515854152463");
postParam.put("franquia", preferences.getFranchise());
postParam.put("sistema", preferences.getSystem());
postParam.put("lista", preferences.getListID());
postParam.put("dataHoraBaixa", "2020-12-03T15:26:22");
postParam.put("foraAlvo", "100");
postParam.put("latitude", "45.545");
postParam.put("longitude", " 45.554");
postParam.put("nivelBateria", "98");
postParam.put("tipoBaixa", "ENTREGA");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, ApiUtils.GET_LIST + preferences.getListID(), new JSONObject(postParam), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "PUTonResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "PUTonResponseError: " + error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String auth1 = "Basic "
+ Base64.encodeToString((preferences.getUserName() + ":" + preferences.getPass()).getBytes(),
Base64.NO_WRAP);
params.put("Authorization", auth1);
params.put("x-ver", "3.0");
params.put("x-ras", "rick");
params.put("Content-Type", "application/json");
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the result in postman:1
Here is the result in postman:2
The problem is there is an array in the api, I've tried the above in the way if there are only JSON object but it is not working, please help me know if anything can be updated or done in different way for sending arrays either in volley or retrofit. Thanks.
//Edit:
I tried sending the params in another way and this was also giving the same 500 error:
JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
try {
jsonObj.put("codHawb", "02305767706");
jsonObj.put("dataHoraBaixa", "2020-12-03T15:26:22");
jsonObj.put("foraAlvo", "100");
jsonObj.put("latitude", "-46.86617505263801");
jsonObj.put("longitude", " -23.214458905023452");
jsonObj.put("nivelBateria", "98");
jsonObj.put("tipoBaixa", "ENTREGA");
jsonArray.put(jsonObj);
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("imei", "514515854152463");
postParam.put("franquia", preferences.getFranchise());
postParam.put("sistema", preferences.getSystem());
postParam.put("lista", preferences.getListID());
postParam.put("entregas",jsonArray.toString());
Finally figured it out, sending the PUT request in the form of api. FYI: If you have multiple json objects inside the array, just use a for loop, here is the working answer:
private void PutJsonRequest() {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
JSONObject jsonObj1=new JSONObject();
try {
jsonObj.put("codHawb", "02305767706");
jsonObj.put("dataHoraBaixa", "2020-12-03T15:26:22");
jsonObj.put("foraAlvo", "100");
jsonObj.put("latitude", "45.222");
jsonObj.put("longitude", " 23.23452");
jsonObj.put("nivelBateria", "98");
jsonObj.put("tipoBaixa", "ENTREGA");
jsonArray.put(jsonObj);
jsonObj1.put("imei", preferences.getIMEI());
jsonObj1.put("franquia", preferences.getFranchise());
jsonObj1.put("sistema", preferences.getSystem());
jsonObj1.put("lista", preferences.getListID());
jsonObj1.put("entregas", jsonArray);
Log.e(TAG, "PutJsonRequest: "+jsonObj1 );
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, ApiUtils.GET_LIST + preferences.getListID(),jsonObj1, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "PUTonResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "PUTonResponseError: " + error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String auth1 = "Basic "
+ Base64.encodeToString((preferences.getUserName() + ":" + preferences.getPaso()).getBytes(),
Base64.NO_WRAP);
params.put("Authorization", auth1);
params.put("x-versao-rt", "3.8.10");
params.put("x-rastreador", "ricardo");
// params.put("Content-Type", "application/json");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
request.setTag(TAG);
queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Comment if anyone has a doubt.

Android Volley GET Request with username and password fails

The following Android Volley GET Request is failing with the following error message:
E/Volley: [1038] BasicNetwork.performRequest: Unexpected response code 401 for
This is the Request:
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
final String url = "https://xxxxxxxx/storage/v1/items";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
StringBuilder formattedResult = new StringBuilder();
JSONArray responseJSONArray = response.getJSONArray("items");
for (int i = 0; i < responseJSONArray.length(); i++) {
formattedResult.append("\n" + responseJSONArray.getJSONObject(i).get("no") + "=> \t" + responseJSONArray.getJSONObject(i).get("ean")
+ "=> \t" + responseJSONArray.getJSONObject(i).get("name")
+ "=> \t" + responseJSONArray.getJSONObject(i).get("type")
+ "=> \t" + responseJSONArray.getJSONObject(i).get("destruction")
+ "=> \t" + responseJSONArray.getJSONObject(i).get("archived")
);
}
txtShowTextResult.setText("List of Items \n" + " Number" + "\t EAN \n" +
"\t Name \n" + "\t Type \n" + formattedResult);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtShowTextResult.setText("An Error occured while making the request");
}
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "username:password";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
}
});
requestQueue.add(jsonObjectRequest);
I am not sure why the Request is failing, as I am new to Android Volley.
Possible cause: the method getHeaders() is not called, but I donĀ“t know where to put the Method call in the Request and therefore, I would appreciate any help, hints or feedback. Thanks in advance!
Adding the missing part at your code you can try out the following. Notice the override part of getHeaders, let me know how it goes.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//handle response
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle error
}
}){
#NotNull
#Override
public Map<String, String> getHeaders() {
//Handle headers inside here
Map<String, String> headers = new HashMap<>();
String credentials = "username:password";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
}
};
requestQueue.add(jsonObjectRequest);

BasicNetwork.performRequest: Unexpected response code 400

I have a big problem. Normally, i did not receive this error anytime. But now i am receiving. How can solve that problem? I research and i learn i need create custom header with getBodyContentType(). But that is not solving for me..
public void getToken(final Activity activity, final String paramUsername, final String paramPassword) {
String tag_json_obj = "getToken";
SharedComponent.pDialog = new ProgressDialog(activity);
SharedComponent.pDialog.setMessage(context.getString(R.string.controlYourInfo));
SharedComponent.pDialog.setCancelable(false);
SharedComponent.pDialog.show();
JSONObject params = new JSONObject();
try {
params.put("username", paramUsername);
params.put("password", paramPassword);
params.put("grant_type", "password");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
WebUrls.getToken, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log.d(TAG, response.toString());
SharedComponent.pDialog.hide();
try {
if (response.toString().contains("error")) {
error = response.getString("error");
error_description = response.getString("error_description");
Toast.makeText(context, error_description, Toast.LENGTH_LONG).show();
} else {
access_token = response.getString("access_token");
token_type = response.getString("token_type");
expires_in = response.getInt("expires_in");
SharedComponent.sharedEditor.putString("TOKEN", "Bearer " + access_token);
SharedComponent.sharedEditor.putString("LOGGED", "LOGGED");
SharedComponent.sharedEditor.commit();
Log.e("TOKEN", "Bearer " + access_token);
Intent intent = new Intent(activity, MainScreen.class);
context.startActivity(intent);
((Activity) context).finish();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
SharedComponent.pDialog.hide();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-Type", getBodyContentType());
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

Volley Offline Working

Ways to implement volley json response cache.I tried the following way to get response from volley.i get the response correctly.I dont know how to store these json values into volley cache
StringRequest strReq = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("mainresp$$$"+response);
Log.d("Volley Request Success", response.toString());
result=response;
callback.onSuccess(result);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley request Error",
"Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
Together with my comments, you have already read my answer at the following question:
Android Setup Volley to use from Cache
I have just tested with POST request, as the following code:
CacheRequest cacheRequest = new CacheRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// Check if it is JSONObject or JSONArray
Object json = new JSONTokener(jsonString).nextValue();
JSONObject jsonObject = new JSONObject();
if (json instanceof JSONObject) {
jsonObject = (JSONObject) json;
} else if (json instanceof JSONArray) {
jsonObject.put("success", json);
} else {
String message = "{\"error\":\"Unknown Error\",\"code\":\"failed\"}";
jsonObject = new JSONObject(message);
}
textView.setText(jsonObject.toString(5));
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
My sample Asp.Net Web API code as the following:
// POST api/<controller>
public IHttpActionResult Post()
{
string jsonString = "[" +
"{" +
"name: \"Person 1\"," +
"age: 30," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 2\"," +
"age: 20," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 3\"," +
"age: 40," +
"type: \"POST\"," +
"}" +
"]";
JArray jsonObj = JArray.Parse(jsonString);
return Ok(jsonObj);
}
Here is the result screenshot

How to use applicaiton-only oauth in twitter?

Can anyone show me how to use the application-only oauth in twitter? I have to implement it in my app but i cant find ANY tutorials on net for the new api 1.1. An example would be much better...
Hi the following code include how to use application-only OAuth and get user_timeline.
download this library http://loopj.com/android-async-http/
use this code
/*
* -url user_timeline
* -client and asyncHttpResponseHandler is used to get timeline
*/
String url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=<NAME>";
AsyncHttpClient client = new AsyncHttpClient();
AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
/*--------- DidReceiveData ---------*/
Log.e("", "JSON FILE "+" response " + response);
};
};
/*
* OAuth Starts Here
*/
RequestParams requestParams = new RequestParams();
requestParams.put("grant_type", "client_credentials");
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.addHeader("Authorization", "Basic " + Base64.encodeToString((CONSUMER_KEY + ":" + CONSUMER_SECRET).getBytes(), Base64.NO_WRAP));
httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpClient.post("https://api.twitter.com/oauth2/token", requestParams, new AsyncHttpResponseHandler() {
public void onSuccess(String responce) {
try {
JSONObject jsonObject = new JSONObject(
responce);
Log.e("", "token_type " + jsonObject.getString("token_type") + " access_token " + jsonObject.getString("access_token"));
client.addHeader("Authorization", jsonObject.getString("token_type") + " " + jsonObject.getString("access_token"));
client.get(url, asyncHttpResponseHandler);
} catch (JSONException e) {
e.printStackTrace();
}
};
public void onFailure(Throwable error, String response) {
Log.e("", "error " + error.toString() + " response " + response);
};
});

Categories

Resources