i have situation here
have some json code in the server side ... here's a part of json
{
"status":"ok",
"count":10,
"count_total":88,
"pages":9,
"posts":
[{
"id":1530,
"type":"post",
"slug":"slug",
""url":"url",
"status":"publish",
"title":"title",
"title_plain":"sth",
"content":"some content",
"modified":"2016-05-22 20:21:47",
"categories":[{"blah":"blah"}]
}]
}
i want "content" under the "posts" array and volley wouldn't let me use jsonarray inside jsonobject .
here's a part of my codes :
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("posts");
}
JSONcatch (JSONException e) {
e.printStackTrace();
}
}
},null);
sorry for the snippet i couldn't insert my code ...
Tnx
Is that a typo or something but your JSON is invalid you are having two double quotes here ""url":"url". Just remove one.
Just do this :
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray obj = response.getJSONArray("posts");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
int id = jsonObject.getInt("id");
String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
},null);
First create Models:
public class CategoryModel
{
public String blah;
}
public class PostModel
{
public int id;
public String type;
public String slug;
public String url;
public String status;
public String title;
public String title_plain;
public String content;
public String modified;
public List<CategoryModel> categories;
}
public class PostsModel
{
public String status;
public int count;
public int count_total;
public int pages;
public List<PostModel> posts;
}
then use gson;
in gradle:
compile 'com.google.code.gson:gson:2.4'
then in code get your object:
JSONObject json;
Gson gson = new Gson();
try {
json = new JSONObject(yourJsonString)
PostsModel result = gson.fromJson(json, PostsModel.class);
return result; // this is your deserialized response object
}catch(Exception e){
}
Volley:
in app class:
private VolleyServiceSingleton mVolleySingleton;
private RequestQueue mVolleyApiClient;
on create:
mVolleySingleton = VolleyServiceSingleton.getInstance();
mVolleyApiClient = mVolleySingleton.gerRequestQueue();
String request:
class VolleyStringRequest extends StringRequest
{
private Map<String, String> mParams;
public VolleyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener, Map<String, String> requestParams) {
super(method, url, listener, errorListener);
mParams = requestParams;
afterRequestErrorRunnable = null;
Log.e("Request",url);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
try {
Log.e("errorResponse", new String( volleyError.networkResponse.data, "utf-8" ));
}catch(Exception e){
}
}
return super.parseNetworkError(volleyError);
}
#Override
public RetryPolicy getRetryPolicy() {
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(
TIMEOUT_IN_MILLISECONDS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Accept-Charset","utf-8");
//headers.put("Accept", RITEAID_HTTP_CONTENT_TYPE);
return headers;
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
and request (this must be customized):
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("sign_in_username_email", Utils.nullToStringOrString(username));
paramMap.put("sign_in_password", password != null ? Utils.passwordConvert(password) : "");
paramMap.put("key", Constants.API_KEY);
mResponseHandler = getResponseHandler(requestUrl, positiveResponseFunc, inClass);
VolleyStringRequest request = new VolleyStringRequest(Request.Method.POST, getFinalUrl(requestUrl, null), getResponseHandler(requestUrl, positiveResponseFunc, inClass), createErrorListener(context, progress), paramMap);
request.setRetryPolicy(mRetryPolicy);
request.setTag(REQUEST_TAG);
mVolleyApiClient.add(request);
Related
What have I done wrong?. How can i resolve this?. Please explain why this error occur. if it is run successfully what is my response?
MainActivity :
public class MainActivity extends AppCompatActivity {
String url = "http://vsstechnology.com/DTSignUp/api/business/create_business.php";
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
HashMap<String, String> params = new HashMap<>();
params.put("address", "xxx");
params.put("business_description", "xx");
params.put("businessEmail", "xxx#gmail.com");
params.put("business_name", "xxx");
params.put("phone", "1234567890");
params.put("business_type", "xx");
params.put("created_by", "xxx");
params.put("customer_name", "xxx");
params.put("email", "yyy#gmail.com");
params.put("firstName", "yyy");
params.put("lastName", "yyy");
params.put("phone", "6544324569");
GsonRequest<Model> gsonRequest = new GsonRequest<Model>(Request.Method.POST, url, Model.class, params, new Response.Listener<Model>() {
#Override
public void onResponse(Model response) {
Toast.makeText(getApplicationContext(), "success" + " " + response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error" + " " + error, Toast.LENGTH_LONG).show();
}
});
requestQueue.add(gsonRequest);
}
}
Model :
public class Model {
private Business business;
private Contacts[] contacts;
private ServerResponse serverResponse;
public Model(Business business, Contacts[] contacts, ServerResponse serverResponse) {
this.business = business;
this.contacts = contacts;
this.serverResponse = serverResponse;
}
public Business getBusiness() {
return business;
}
public void setBusiness(Business business) {
this.business = business;
}
public Contacts[] getContacts() {
return contacts;
}
public void setContacts(Contacts[] contacts) {
this.contacts = contacts;
}
public ServerResponse getServerResponse() {
return serverResponse;
}
public void setServerResponse(ServerResponse serverResponse) {
this.serverResponse = serverResponse;
}
}
custom GsonRequest :
public class GsonRequest<T> extends Request<T> {
private Gson gson = new Gson();
private Class<T> clazz;
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param params Map of request headers
*/
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> params,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.headers = null;
this.params = params;
this.listener = listener;
gson = new Gson();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
Error :
com.android.volley.ParseError : com.Google.gson.JsonSyntaxException:
java.lang.illegalStateException: Expected BEGIN_OBJECT but was STRING
at line 1 column 1 path $
Based on your error some thing is wrong with your API, to debug it you can use Postman.
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 am using Google's Volley to make GET and POST requests using the following custom request class:
public class GsonRequest<T> extends Request<T> {
private static final int SOCKET_TIMEOUT_MS = 30000;
private static final int MAX_RETRIES = 3;
private final Gson gson = new Gson();
private final Type type;
private final Map<String, String> params;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param type Relevant type object, for Gson's reflection
* #param params Map of request params
*/
public GsonRequest(int method, String url, Type type, Map<String, String> params,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.type = type;
this.params = params;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Here is my question, can I add a param value as JSONArray? like this:
params.put("orderValue", "35");
params.put("price", ""price": ["13.00", "22.00"]");
return params != null ? params : super.getParams();
}
#Override
public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
final RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return super.setRetryPolicy(policy);
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Log.i("" + gson.toJson(params).getBytes("utf-8"));
return gson.toJson(params).getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", gson.toJson(params), "utf-8");
return super.getBody();
}
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
final String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success(gson.fromJson(json, type), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
The Json I'm trying to send:
{
"orderValue": "35",
"price": [
"13.00",
"22.00"
]
}
What is really sent as I get from getBody() method log is:
{
"price": "[\"23.00\",\"55.00\"]",
"orderValue": "35"
}
Any help with this issue?
You need change extends Request to ** JsonObjectRequest** or create JSONArrayRequest object.
public class VolleyJSONObjectRequest extends JsonObjectRequest {
private Context context;
private int timeOut = 10000;
private int maxRetries = 1;
public VolleyJSONObjectRequest(int method, Context context, String url, JSONObject jsonObject, Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, jsonObject, listener, errorListener);
super.setRetryPolicy(new DefaultRetryPolicy(timeOut, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void startRequest() {
VolleyHandler.get(context).addToRequestQueue(this);
}
}
Example method:
private void saveItems(){
if (itens != null && itens.size() > 0) {
try {
JSONArray itensJson = new JSONArray();
for (SalesOrderItem item : itens) { // your loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("price", this.priceOne);
jsonObject.put("price", this.priceTwo);
itensJson.put(jsonObject);
}
JSONObject headerJSON = new JSONObject();
headerJSON.put("price", itensJson);
VolleyJSONObjectRequest request = new VolleyJSONObjectRequest(Request.Method.POST, context, context.getString(R.string.URL_SALES_ORDER_ITENS_INSERT), headerJSON, onResponseItem, onErrorResponseItem);
request.startRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
request = new VolleyStringRequest(context, context.getString(R.string.URL_FINISH_SALES_ORDER_DRAFT), onResponseFinishSalesOrderDraft, onErrorResponseFinishSalesOrderDraft);
request.startRequest();
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
I making an app and in a specific part I send a string and receive a json. I USE VOLLEY
It works good, but now i need to send a json.
HERE IS MY CODE:
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
HERE:
public class Config {
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
public static final String KEY_NAME = "COD_ALUMNO";
public static final String KEY_ADDRESS = "COD_ASIGNATURA";
public static final String KEY_VC = "GRUPO_SECCION";
public static final String KEY_AULA = "AULA";
public static final String KEY_DIA = "DIA";
public static final String KEY_INICIO = "INICIO";
public static final String KEY_FIN = "FIN";
public static final String JSON_ARRAY = "result";
}
AND HERE IS THE PART OF VOLLEY CODE
public class TabsActivity extends AppCompatActivity implements
View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
int cont=1;
String[ ] contenido = new String[7];
String f="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainint);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
Toast.makeText(getBaseContext(), "si", Toast.LENGTH_LONG).show();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TabsActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
String name="";
String address="";
String grupo = "";
String aula = "";
String dia = "";
String inicio = "";
String fin = "";
try {
Toast.makeText(getBaseContext(), "LOGIN... ", Toast.LENGTH_LONG).show();
JSONObject jsonObject = new JSONObject(response);
JSONArray ja = jsonObject.getJSONArray("orders");
// JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
for (int i = 0; i < ja.length(); i++) {
JSONObject collegeData = ja.getJSONObject(i);
name = collegeData.getString("id");
address = collegeData.getString("item");
grupo = collegeData.getString("GRUPO_SECCION");
aula = collegeData.getString("AULA");
dia = collegeData.getString("DIA");
inicio = collegeData.getString("INICIO");
fin = collegeData.getString("FIN");
///database
DBAdapter db= new DBAdapter(this);
db.open();
long id = db.insertContact(address, aula,dia,inicio,fin );
db.close();
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{ do{
contenido=getcontenido(c);
}while (c.moveToNext());
}
db.close();
cont= Integer.parseInt( contenido[0]);
/// database
/// alarms
int [] time;
time = parsetime(inicio);
int horai = time[0];
int minutoi = time[1];
int diaa = getDay(dia);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, horai);
cal.set(Calendar.MINUTE, minutoi);
cal.set(Calendar.DAY_OF_WEEK, diaa);
cal.add(Calendar.SECOND, 2);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.putExtra("name", address);
//intent.putExtra("curos bn",1);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(getBaseContext(),
cont+1, intent, PendingIntent.FLAG_UPDATE_CURRENT );
AlarmManager alarmManager =
(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);
////alarms
f=f+"codigo alumno:\t"+name+"\ncodigo/nombre curso:\t" +address+ "\ngrupo:\t"+grupo+"\naula:\t"
+aula+"\ndia:\t"+dia+"\ninicio:\t"+inicio+"\nfin:\t"+fin+"\n:\t";
}
// Toast.makeText(getBaseContext(), collegeData.length(), Toast.LENGTH_LONG).show();
//collegeData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText(f);
}
I JUS SENT THE STRING editTextId.getText() . That is a code for each user , but now i need to send a json with that string .
'CCODUSU' '45875621'
CCODUSU is the identifier
I would take a look at StringRequests. Here is an example of how to send things to a PHP file, which updates a database, or can do whatever:
SetMyStuff.java:
package com.example.your_app.database_requests;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class SetMyStuff extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://example.com/SetMyStuff.php";
private Map<String, String> params;
public SetMyStuff(String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
To call this StringRequest:
Response.Listener<String> listener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (!success) {
Log.e(TAG, "Could not update stuff.");
} else {
Log.e(TAG, "Updated stuff.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SetMyStuff setMyStuffRequest = new SetMyStuff(username, password, listener);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(setMyStuffRequest);
The PHP file that recieves this:
<?php
$password = $_POST["password"];
$username = $_POST["username"];
$con = mysqli_connect("website.com", "dbusername", "dbpassword", "dbtable");
$response = array();
$response["success"] = false;
/* Do something */
$response["success"] = true;
echo json_encode($response);
?>
Do you mean you need send a JSON which contains the editTextId.getText().toString().trim(), if you want to do this, you must spell out a complete and correct JSON.
'CCODUSU' '45875621'
The string you post is not a json, you need to modify it into this:
{"CCODUSU": "45875621"}
Once you give this string after your Config.DATA_URL, the server will receive the id parameter and it is the JSON.
I also came up with this same issue.On the course of finding way I have developed a way that might help you.
If you want to post json to the server then you can create JsonObjectRequest as:
public class AppJSONObjectRequest extends JsonObjectRequest{
private Response.Listener<JSONObject> listener;
private Map<String, String> headers;
public AppJSONObjectRequest(int method, String url, JSONObject jsonObject, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener, Map<String, String> headers) {
super(method, url, jsonObject, reponseListener, errorListener);
this.headers = headers;
this.listener = reponseListener;
}
#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 void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
}
And then you can use this jave file in your activity or fragment to send json and recieve response like this below:
JSONObject parameters = new JSONObject();
try {
parameters.put("f_name", "name1");
parameters.put("l_name", "name2");
.......
}catch (Exception e){
e.printStackTrace();
}
AppJSONObjectRequest objectRequest = new AppJSONObjectRequest(Request.Method.PUT, url, parameters, RequestSuccessListener, RequestErrorListener, getHeaders); //headers if u have
//url: your request base url
VolleySingleton volleySingleton = VolleySingleton.getInstance(this);
volleySingleton.addToRequestQueue(objectRequest);
And you can receive json as :
Response.Listener<JSONObject> RequestSuccessListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Response" + " " + response);
}
};
Response.ErrorListener RequestErrorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
you can get headers as:
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("x-auth-token", Constant.API_KEY_X_AUTH_TOKEN);
return headers;
}
VolleySingleton class
public class VolleySingleton {
private static VolleySingleton mInstance;
private Context mContext;
private RequestQueue mRequestQueue;
private VolleySingleton(Context context){
this.mContext = context;
mRequestQueue = getRequestQueue() ;
}
public static synchronized VolleySingleton getInstance(Context context){
if(mInstance == null){
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req){
getRequestQueue().add(req);
}
}
Just you can implement above sample... then hope you will get what you want.it may be copy paste code but it covers overall enough to solve your problem.