How I send a JsonObject and recive a JsonArray - android

While I was testing the "volley" library, a doubt arose me regarding the method "post".
The thing is that I have been working with JsonObject until now, for that I used the following code and it works. In this method I send and JsonObject and receive another JsonObjet, I had no problem with it.
Now my doubt is, How can I do to send a JsonObject and receive an ArrayObject?
I am really lost with this, I will really appreciate your help, thanks in advance
public void testPost(String url, final String tag, JSONObject obj) {
//final ProgressDialog pDialog = new ProgressDialog(context);
//pDialog.setMessage("Loading...");
//pDialog.show();
JsonObjectRequest jsonObjReqpost = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//test
Log.d("SendRequestJsonPost", response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.data != null) {
error = new VolleyError(new String(error.networkResponse.data));
}
String fail = handlingErrors.resolverErrors(error.toString());
//Log.d("SendRequestJsonPost", fail);
//pDialog.hide();
}
}) {
//header
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("charset", "utf-8");
return headers;
}
};
jsonObjReqpost.setTag(tag);
Singleton.getInstance(context).addToRequestQueue(jsonObjReqpost);
}

You can use the following method to get JsonArray as response.
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener)
{
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
Please refer this answer for more details.

public class nameOfClass extends AsyncTask {
String response;
//This process is work in Background
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token;
//Tocken name that is send to server
token = "TockenName|" + "|";
try {
response = connection.EstablishConnection(token);
String message = "Sorry Fail to connect";
if (response.equals(message)) {
onPostExecute(message);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// In this method you can open loading msg
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
//Json object
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
//Hear traverse the loop and get the data
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Related

How to Posting Json object as request and getting jsonArray in android using Volley Library?

I am new to Volley Libary can you guide how to get the JSONArray response for JSONObject as the request.
RequestQueue MyRequestQueue = Volley.newRequestQueue(Register.this);
String u = your url;
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, u, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject res = new JSONObject(response); // getting response object
JSONObject data = res.getJSONObject("Response");
login_userid = data.getString("_id"); //get the string
Ins_name = data.getString("Inscube_Name");
User_Email = data.getString("Email");
Color_code = data.getString("Color_Code");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this, " " + error, Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> para = new HashMap<String, String>();
para.put("",my); //put your post string here
para.put("", reg_email);
para.put("", reg_pass);
para.put("", my);
return para;
}
};
MyStringRequest.setRetryPolicy(new DefaultRetryPolicy(8000, 3, 2));
MyRequestQueue.add(MyStringRequest);
}
Looks like you can easily modify this constructor and add to JsonArrayRequest.
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}

Volley onResponse method not working

I'm using Volley to send Post request.I'm trying to send jsonObject to server.This is my source
public void sendDicieIDToServer(JSONObject jsonObject)
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("response is", "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
NetworkResponse errorRes = volleyError.networkResponse;
String stringData = "";
if(errorRes != null && errorRes.data != null){
try {
stringData = new String(errorRes.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Log.e("Error",stringData);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization",uhfScannerModel.getToken());
params.put("Content-Type", "application/json");
return params;
}
};
HandsetApplication.getInstance().addToRequestQueue(jsonObjectRequest);
}
I successfully created JsonObject and when I run my app and try to debug it, onErrorResponse method has called and stringData String contains real json result. I don't know what is a wrong and why onErrorResponse method calling.
User this link for Volley
Here i made volley reusability where you can apiCall easy way..
https://github.com/sikander-kh/Volley-Reusability

Json takes multiple attempts to get downloaded correctly

I am asking the same question I asked previously as I'm unable to solve the issue. You can follow the link: https://stackoverflow.com/questions/40017707/unable-to-get-correct-json
Don't be judgemental before trying it manually at your end.I'd like to know where am I mistaking here.
Thanks
Older Post:-
I've 1 url: http://alolma.coderswebsites.com/api/v1/person/ and I tried following diff libs but unable to parse the correct json.
It shows org.json.JSONException: Unterminated string at character 21001 while using okhttp.
� while using volley (with parseNetworkResponse also).
com.loopj.android:android-async-http:1.4.9- it aprses the json but here, new issues arises that the size of the result array varies (I don't know how) & I use the count jsonobj to match the size of it but it takes 5-8 hits to get the correct json data.
Plz help me and let me know wh this happening, the data is in UT-8 already,so I did not decode it.
Volley coding:-
public void getPersonList(Context context) {
UTF8StringRequest stringRequest = new UTF8StringRequest (com.android.volley.Request.Method.GET,"http://alolma.coderswebsites.com/api/v1/person/",
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response",response);
try{
list.clear();
JSONObject obj = new JSONObject(response);
count=obj.getInt("count");
Log.d("count",""+count);
Log.d("lenofresult",""+obj.getJSONArray("results").length());
for (int i=0; i<obj.getJSONArray("results").length(); i++) {
Person person = new Person();
person.parse(obj.getJSONArray("results").getJSONObject(i));
list.add(person);
}
Log.d("list.siz()",""+list.size());
if (list.size()==count)
{ Log.d("data","100%");
loadagain=false;
list2=list;
callBack.onSuccess();
}
}
catch (Exception e){}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
For this I use -
public class UTF8StringRequest extends StringRequest {
public UTF8StringRequest(int method, String url, com.android.volley.Response.Listener listener, com.android.volley.Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
public UTF8StringRequest(String url, com.android.volley.Response.Listener<String> listener, com.android.volley.Response.ErrorListener errorListener) {
super(url, listener, errorListener);
}
#Override
protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
String utf8String = null;
try {
utf8String = new String(response.data, "UTF-8");
return com.android.volley.Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return com.android.volley.Response.error(new ParseError(e));
}
}
}
try asynctask-
class getdata extends AsyncTask {
#Override
protected void onPreExecute() {
loadagain=false;
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
Log.d("inside","getunseenmsg");
String s="";
URL url = null;
try {
url = new URL("http://alolma.coderswebsites.com/api/v1/person/");
final InputStream inputStream = url.openStream();
final InputStreamReader inputStreamReader
= new InputStreamReader(inputStream, "UTF-8");
StringBuffer stringBuffer = new StringBuffer();
char[] buffer = new char[2000];
while (inputStreamReader.read(buffer, 0, 2000) != -1) {
stringBuffer.append(buffer);
}
Log.d("RAW_STRING", stringBuffer.toString());
list.clear();
JSONObject obj = new JSONObject(stringBuffer.toString());
inputStreamReader.close();
count=obj.getInt("count");
Log.d("count",""+count);
Log.d("lenofresult",""+obj.getJSONArray("results").length());
for (int i=0; i<obj.getJSONArray("results").length(); i++) {
Person person = new Person();
person.parse(obj.getJSONArray("results").getJSONObject(i));
list.add(person);
}
Log.d("list.siz()",""+list.size());
if (list.size()==count)
{ Log.d("data","100%");
loadagain=false;
list2=list;
callBack.onSuccess();
}
else
{ loadagain=true;
getPersonList();}
} catch (Exception e) {
e.printStackTrace();
Log.d("list.siz()",""+list.size());
list.clear();
if (list.size()==count & count>0)
{Log.d("data","100%");
loadagain=false;
list2.addAll(list);
callBack.onSuccess();
}
else
{ loadagain=true;
getPersonList();}
}
return s;
// TODO Auto-generated method stub
}
protected void onPostExecute(String params) {
super.onPostExecute(params);
}
}

Basic Authentication not working in Volley in android

I am using volley library but when I use basic authentication then I do not got any response and also volley is not showing any error. I am also try HttpUrlConnection with Asyntask but I face same problem. Please provide solution this problem.
I also hit my api via Postman client, ARC and my api is working fine with these client.
MyJsonObjectRequest.java
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {
private Priority priority = null;
//private Map<String, String> headers = new HashMap<String, String>();
public MyJsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
public MyJsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
#Override
public Priority getPriority() {
if (this.priority != null) {
return priority;
} else {
return Priority.NORMAL;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//Log.e("JSON"," AUTH CODE "+createBasicAuthHeader("MaS", "123456"));
return createBasicAuthHeader("username", "123456");
}
Map<String, String> createBasicAuthHeader(String username, String password) {
Map<String, String> headerMap = new HashMap<String, String>();
String credentials = username + ":" + password;
String encodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headerMap.put("Content-Type", "application/json; charset=utf-8");
headerMap.put("Authorization", "Basic " + encodedCredentials);
return headerMap;
}
public void setHeader(String title, String content) {
// headers.put(title, content);
}
public void setPriority(Priority priority) {
this.priority = priority;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError){
NetworkResponse response = volleyError.networkResponse;
if (response!=null)
{
Log.e("TAG"," VOLLEY ERROR1 "+response.statusCode);
}
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
Log.e("TAG"," VOLLEY ERROR "+error.toString());
volleyError = error;
}
return volleyError;
}
}
My MainActvity
public class JsonObjectActivity extends AppCompatActivity {
JsonObjectRequest gsonRequest;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_object);
textView = (TextView) findViewById(R.id.tv2);
try {
doingProcessJsonArray();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void doingProcessJsonArray() throws JSONException {
// i am use local server like
String newUrl="http://myserver:8023/Users.svc/password_encrypt";
JSONObject params = new JSONObject();
params.put("PASSWORD", "12345655");
//params.put("domain", "http://samset.info");
gsonRequest =new JsonObjectRequest(Request.Method.POST,newUrl, params, successListener(), errorListener());
Constants.showProgressDialog(this, "Loading..");
//gsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Start progressbar
// gsonRequest.setPriority(Request.Priority.IMMEDIATE);
Log.e("TAG"," request "+gsonRequest.toString());
VolleySingleton.getInstance(this).addToRequestQueue(gsonRequest, "volleyrequest");
}
private Response.ErrorListener errorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error "+error.toString());
}
};
}
public Response.Listener successListener()
{
return new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Constants.dismissDialog();
Log.e("Volley","Responce "+response.toString());
textView.setText("JSONObject RESPONCE > "+response.toString());
}
};
}
}
postman screen shot

Volley Request Body not being execulted

I have the following method in Volley.When i call the method only one Log info gets printed in log.
private void loadFromCloudAPI() {
Log.i("apiresponse","inside api call");
queue = VolleySingleton.getInstance().getQueue();
CacheRequest attendanceDetailsCache = new CacheRequest(Request.Method.POST, URL, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
final String jsonString;
Log.i("apiresponse","inside api call");
try {
jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i("apiresponse",jsonString);
JSONArray jsonArray= new JSONArray(jsonString);
renderDataInTheAttendanceDetailsLayout(jsonArray);
} catch (UnsupportedEncodingException|JSONException e) {
Log.i("apiresponse",e+"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String ,String > data = new HashMap<>();
data.put("authenticate","false");
data.put("class_id","1");
data.put("section_id","4");
data.put("student_id","1");
return super.getParams();
}
};
attendanceDetailsCache.setTag(this);
queue.add(attendanceDetailsCache);
}
Output::
apiresponse: inside api call
Only one info Log ? How ? I cannot log the response nor the error , when i try the same thing using ARC in browser i get the response. What might be the issue ?

Categories

Resources