Someone to help me about this error
image of my screen
thanks!
You must diklaration/adding a ErrorListener
public class MyRequest {
private Context context;
private RequestQueue queue;
public MyRequest(Context context, RequestQueue queue) {
this.context = context;
this.queue = queue;
}
public void register(String pseudo, String password, String password2) {
String url = "http://192.168.56.1/don/connexion.php";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
Your Question about Post Request but Your Code is Get Request.......
try this for POST,
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Success
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_USERNAME, user);
params.put(KEY_PASSWORD, pass);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(stringRequest);
and you have to pass some params if you need to use Post method
Related
In my Project if I add parameters with url and then make a request that is being received by the server. But if I use GET params method then the request is not being received by the server.
Successful request
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText name1=(EditText)findViewById(R.id.editText);
final EditText price1=(EditText)findViewById(R.id.editText2);
final EditText description1=(EditText)findViewById(R.id.editText3);
Button submit=(Button)findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onClick(View v) {
final String name=name1.getText().toString();
final double price= Double.parseDouble(price1.getText().toString());
final String description=description1.getText().toString();
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://192.168.0.101/webservice/create_product.php?name=symphony&price=1000&description=from_android";
StringRequest sr=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo=new JSONObject(response);
Log.d("From Volley",+jo.getInt("success")+" "+jo.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("From Volley", error.getMessage());
}
});
Log.d("From Volley",sr.getUrl()+" "+sr.toString());
queue.add(sr);
}
});
}
}
Failed request
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText name1=(EditText)findViewById(R.id.editText);
final EditText price1=(EditText)findViewById(R.id.editText2);
final EditText description1=(EditText)findViewById(R.id.editText3);
Button submit=(Button)findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onClick(View v) {
final String name=name1.getText().toString();
final double price= Double.parseDouble(price1.getText().toString());
final String description=description1.getText().toString();
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://192.168.0.101/webservice/create_product.php";
StringRequest sr=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo=new JSONObject(response);
Log.d("From Volley",+jo.getInt("success")+" "+jo.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("From Volley", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("name",name);
params.put("price", String.valueOf(price));
params.put("description",description);
return params;
}
};
Log.d("From Volley",sr.getUrl()+" "+sr.toString());
queue.add(sr);
}
});
}
}
Here you use GET method that you have to build URL before make request, getParams() is used when request method is post...
Build URL for GET As follow
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("192.168.0.101")
.appendPath("webservice")
.appendPath("create_product.php")
.appendQueryParameter("name", name)
.appendQueryParameter("price", String.valueOf(price))
.appendQueryParameter("description", description);
String url = builder.build().toString();
StringRequest sr=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
}
change to
StringRequest sr=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
}
I am having problem with this method using Volley in my Android app. From my debugging it seems like the code never runs for some reason. I can't seem to find any solution, and I got no errors while running the app.
Could someone please help, and provide some code/solution.
Thanks in advance.
RequestQueue queue;
// My nav-drawer and some other code removed. That is not relevant.
public void registerPushToken(Context context,final String device_uuid,final String device_type, final String push_token){
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,"http://app.Myapp.com/api/v2/pushtokens", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("device_uuid", String.valueOf(FragmentedUser.getUniquePsuedoID()));
params.put("device_type", "android");
params.put("push_token",String.valueOf(Batch.Push.getLastKnownPushToken()));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
queue.start();
}
I split the whole code into a new class
public class PushTokenRegister {
public static void registerPushToken(Context context) {
RequestQueue queue = Volley.newRequestQueue(context);
String url = "http://app.MYAPP.com/api/v2/pushtokens";
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("onResponse", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("device_uuid", String.valueOf(FragmentedUser.getUniquePsuedoID()));
params.put("device_type", "android");
params.put("push_token",String.valueOf(Batch.Push.getLastKnownPushToken()));
return params;
}
};
queue.add(strRequest);
queue.start();
}
}
And call it from this method inside mainActivity:
PushTokenRegister.registerPushToken(getBaseContext());
I'm trying to post data to website. It is login operation. I check form data hidden tag etc. In form data there is a hidden input _RequestVerificationToken. That's why first, I made get request to parse _RequestVerificationToken and for headers.
StringRequest _StringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Parsing Process
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
)
{
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
headers=response.headers;
return super.parseNetworkResponse(response);
}
};
After all i made post request with parameters and headers:
#Override
public Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("Password", password);
params.put("RememberMe", "false");
params.put("ReturnUrl", url_post);
params.put("UserName",username);
params.put(name,_RequestVerificationToken);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
I check form data by using fiddler extension in chrome. I checked parameters again and again but it returned code 400. Can you show me what is the problem?
Change Request.Method.GET to Request.Method.POST
StringRequest _StringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Parsing Process
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
)
{
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
headers=response.headers;
return super.parseNetworkResponse(response);
}
};
Or You can use this code:-
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
returnValue = response;
try {
parseFromUrl(response);
System.out.println(returnValue);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(app,error.toString(),Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Password", password);
params.put("RememberMe", "false");
params.put("ReturnUrl", url_post);
params.put("UserName",username);
params.put(name,_RequestVerificationToken);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(app);
requestQueue.add(stringRequest);
I solve the problem with this class and I added this:
CookieManager cookieManager = new CookieManager(new PersistentCookieStore(this), CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(cookieManager);
before add request to queue
Can any one suggest in Android volley library only post request.
I don't want to wait for response.
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
common.toast(getApplicationContext().getApplicationContext(), error.getMessage());
loader(false);
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tagStringReq);
I have a Volley Request code
RequestQueue queue = Volley.newRequestQueue(this);
String url =<My URL>;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
How do I set a header called Authorization in this??
Override getHeaders in request like:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = super.getHeaders();
if(params==null)params = new HashMap<>();
params.put("Authorization","Your authorization");
//..add other headers
return params;
}
};
you can write a class extends Request.(override getHeaders() and so on)
just like
public abstract class AbsRequest<T> extends Request<T>{
public AbsRequest(int method, String url, Response.ErrorListener listener) {
this(method, url, null, listener);
}
public AbsRequest(int method, String url, Map<String, String> params, Response.ErrorListener listener) {
this(method, url, params, null, listener);
}
public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, Response.ErrorListener listener) {
this(method, url, params, head, null, listener);
}
public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
this(method, url, params, null, head, bodyContentType, listener);
}
public AbsRequest(int method, String url, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
this(method, url, null, body, head, bodyContentType, listener);
}
private AbsRequest(int method, String url, Map<String, String> params, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
super(method, url, listener);
}
}
for more information you can see https://github.com/Caij/CodeHub/blob/master/lib/src/main/java/com/caij/lib/volley/request/AbsRequest.java
how to use can see https://github.com/Caij/CodeHub/tree/master/app/src/main/java/com/caij/codehub/presenter/imp
A call to super.getHeaders() throws UnSupportedOperationException.
remove super.getHeaders() to get rid off that.
This here is a sample volley request showing how to add headers
private void call_api(final String url){
if(!this.isFinishing() && getApplicationContext() != null){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
resultsTextView.setVisibility(View.INVISIBLE);
loader.setVisibility(View.VISIBLE);
}
});
Log.e("APICALL", "\n token: " + url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("APICALL", "\n response: " + response);
if(!FinalActivity.this.isFinishing()){
try {
JSONObject response_json_object = new JSONObject(response);
JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
last_results_type = k.getString("type");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
loader.setVisibility(View.INVISIBLE);
resultsTextView.setText(result);
resultsTextView.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
finish();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("APICALL", "\n error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
finish();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("apiUser", "user");
headers.put("apiKey", "key");
headers.put("Accept", "application/json");
//headers.put("Contenttype", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("location", "10.12 12.32");
return map;
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}