I'm trying to get an identification cookie sent from a website, and for this i'm using Volley library.
First of all, yes i have searched this subject extensively for the past couple of days and using all the answers i managed to rack up this code:
public class Login extends AppCompatActivity {
StringRequest stringRequest = null;
RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
queue = Volley.newRequestQueue(this);
Button b = (Button) findViewById(R.id.bauth);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String url = "http://daviddurand.info/D228/pizza/?action=login&user=david";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
try {
Log.d("URI 1", manager.getCookieStore().get(new URI("http://daviddurand.info/D228/pizza/?action=login&user=david")).toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("URIS", manager.getCookieStore().getURIs().toString());
Log.d("COOKIE", manager.getCookieStore().getCookies().toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
});
}
}
Which does not return anything more than empty brackets, so i'm guessing something(s) wrong..
For starters am i heading the right way here? and what exactly do i need to add to make this work?
you dont need to put this:
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
in your response. but only once before you start making calls.
Using CookieHandler HttpURLConnection, which apparently is the http stack you use :), takes care of the cookies so you need to take care of that in Volley itself.
so you can do
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
just before queue = Volley.newRequestQueue(this);
Related
I'm trying to use volley to make a request to this api (specifically the /BusinessTypes/basic endpoint) in order to get a list of types of catering businesses in the UK, but I keep getting an error.
Initially, I tried to retrieve the data during the onCreate method which is what I thought might have been the problem (however, ideally this is what I want to be able to do). After creating a test button on a blank activity and hooking that up to the code that makes the request, I still have the same problem.
I'm targeting API 21 (Not my choice & can't be changed).
This is the code corresponding to the plain activity with a single button that has id "but".
public class BasicActivity extends AppCompatActivity {
final String FSA_EP_T = "http://api.ratings.food.gov.uk/BusinessTypes/basic";
final String FSA_EP_R = "http://api.ratings.food.gov.uk/Regions";
final String FSA_EP_A = "http://api.ratings.food.gov.uk/Authorities/basic";
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_search);
b = findViewById(R.id.but);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doStuff();
}
});
}
private void doStuff() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest typeRequest = new JsonArrayRequest(
Request.Method.GET,
FSA_EP_T,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("businessType", String.valueOf(response));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyErr", "I keep seeing this!!!");
}
}
) {
#Override
public Map<String,String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
//The api requires me to specify the api version
params.put("x-api-version","2");
params.put("accept", "application/json");
return params;
}
};
typeRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(typeRequest);
}
}
After some playing around I finally realised my problem.
The api endpoint I am using returns a json object which contains a json array, not just a single json array like I assumed it would.
I extracted the array I needed using
response.getJSONArray("businessType");
where response is now a JSONObject.
I assumed an error like this would have shown up automatically in my log but it didn't.
For anyone else having similar problems, I recommend adding
Log.e("VolleyError", error.getMessage());
to the onErrorResponse method.
So I've run into a problem in my code, where I need to get a JSONString from my server with volley. And then I have to parse the String into a JSONObject and then continue doing stuff with that.
My problem here is, that Volley gives the response too late, meaning my string that I want to parse is always empty because its not initialised yet.
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.GET, searchURLBuilder, future, future);
// new Response.Listener<String>() {
// #Override
// public void onResponse(String response) {
// writeToSharedResponse(response_for_search, response);
// }
// },
// new Response.ErrorListener() {
// #Override
// public void onErrorResponse(VolleyError error) {
// Log.d("Error!!:" + error.getMessage(), "");
// }
// });
requestQueue.add(stringRequest);
String response = "";
try {
response = future.get(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
String responseString = m.getString(response_for_search, new String());
pieceDTOList = getPiecesDTOFromJSON(responseString);
Here is a snippet of my code. As you can see I already tried to make a "future" call to block and wait for the answer, but it just times out every time. The commented out bit, is the part I actually wanted to use from the beginning, but that returns the response to late. Since its asynchronous and accesses the server w/e it wants.
writeToSharedResponse just writes the answer into a sharedPreferences variable.
private SharedPreferences m;
private SharedPreferences.Editor editor;
private RequestQueue requestQueue;
public DbParser(Context c) {
m = PreferenceManager.getDefaultSharedPreferences(c);
editor = m.edit();
requestQueue = Volley.newRequestQueue(c);
}
My Question here is: Is there an easy way I can "wait" for the answer from volley so I can continue to work with the response that I get?
Edit 1:
I now added an interface and changed the code around to this:
getString(new VolleyCallback() {
#Override
public void onSuccess(String result) {
getPiecesDTOFromJSON(result);
}
}, searchURLBuilder);
return globalPieceDTOList;
}
private void getString(final VolleyCallback callback, String searchUrl){
StringRequest stringRequest = new StringRequest(Request.Method.GET, searchUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error!!:" + error.getMessage(), "");
}
});
requestQueue.add(stringRequest);
}
Since I cant get the values out of my inner classes, I did a nasty hack and created a global list for my DTO's. The problem now is that "return globalPieceDTOList" is always Null. And again - I would need to "wait" for the Volley response.
Volley requests are async, so when you try to return a value, the request is likely not done yet. If you want to return values from a Volley request use callback interfaces.
Example
public void getString(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do some things here
callback.onSuccess(<PASS STRING RESULT HERE>);
}
});
}
public interface VolleyCallback{
void onSuccess(String result);
}
Example usage:
public void onResume(){
super.onResume();
getString(new VolleyCallback(){
#Override
public void onSuccess(String result){
//do stuff here with the result from the volley request
}
});
}
New to volley.
Quick question.
I can get volley simple HTTP request to work fine when placed in onCreate
Is it possible to put the request into a separate class?
Android studio cannot resolve "stringRequest" in this example. Help much appreciated...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retriever go = new Retriever();
go.queue.add(stringRequest);
}
public class Retriever {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "http://www.google.com";
public StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// mTextView.setText("Response is: " + response.substring(0, 500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mTextView.setText("That didnt work!");
}
});
}
}
Since your stringRequest variable is in the scope of Retriever class, its visibility is contained in that class only. That's why you are getting that error.
It will go away if you write
go.queue.add(go.stringRequest);
as you are referencing the object from the instance of its class.
I have recently started on Android development platform. I am using Android Studio, and using Volley library for network operation. I have implemented a backend for push notification for iOS and it is working very well, and now I am triggering this php via Volley network operation as follows.
For some reasons it calls that URL multiple times (5 or 6 times), how do I know? because iOS device receives multiple notifications. I am not sure why this happens and how I could solve it?
public void onClick(View v) {
if(v == buttonBuy) {
message = (EditText) findViewById(R.id.offerText);
buy();
}
}
private void buy()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, Config.ASK_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("token",token);
params.put("pname",objee.optString("pname"));
params.put("toid",objee.optString("uid"));
params.put("pid",pid);
params.put("message",message.getText().toString().trim());
return params;
}
};
CustomVolleyRequest.getInstance(this).getRequestQueue().add(postRequest);
}
Try to add the following code:
int socketTimeout = 10000; //10 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
i'm trying to use simple Volley JsonObjectRequest fro web service but i get this error:
error: reference to JsonObjectRequest is ambiguous, both constructor JsonObjectRequest(int,String,String,Listener<JSONObject>,ErrorListener) in JsonObjectRequest and constructor JsonObjectRequest(int,String,JSONObject,Listener<JSONObject>,ErrorListener) in JsonObjectRequest match
i'm install volley from Gradle and this is my simple code which i'm using in project.
public class Simple_JsonRequest extends Activity {
private TextView mTvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act__json_request);
mTvResult = (TextView) findViewById(R.id.tv_result);
Button btnJsonRequest = (Button) findViewById(R.id.btn_json_request);
btnJsonRequest.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.GET,
"http://echo.jsontest.com/key/value/one/two",
null,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
}
});
}
private Response.Listener<JSONObject> createMyReqSuccessListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
mTvResult.setText(response.getString("one"));
} catch (JSONException e) {
mTvResult.setText("Parse error");
}
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTvResult.setText(error.getMessage());
}
};
}
}
How about you replace the null which is the 3rd argument, with something more specific and then try ?
Because JsonObjectRequest have two constructors,
one is
JsonObjectRequest(int,String,JSONObject,Listener<JSONObject>,ErrorListener)
and another is
JsonObjectRequest(int,String,String,Listener<JSONObject>,ErrorListener),so if you set the third parameter to null,the compiler won't know which constructor you want to use,so such an error occurred.
To solve your problem,you just can replace your third parameter to new JSONObject() or "".