Can't make a POST request to Github API - android

I am trying to make a POST request to this URL :
"https://api.github.com/search/repositories?q=created:%3E2018-12-29&sort=stars&order=desc"
using the parameters : 'q' , 'sort' and 'order', but I get a message saying the 'q' code is missing.
Request parameters
Response message
It also doesn't work on my android volley using the POST method :
RequestQueue mQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST,"https://api.github.com/search/repositories", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("ANANAS","ONRESPONSE");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ANANAS","ONERROR");
Log.d("ANANAS",error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<String,String>();
params.put("q","created:>2018-12-13");
params.put("sort","stars");
params.put("order","desc");
return params;
}
};
mQueue.add(request);
What am I missing ?

Your parameters are fine, but you should use Request.Method.GET since the API will be expecting a GET (see API docs).
StringRequest request = new StringRequest(Request.Method.GET,"https://api.github.com/search/repositories"

Related

How to access a password protected URL in android using volley library

I am trying to do the following task:
I am planning to use JsonObjectRequest (Volley Library) in my code and extract the credentials but I am not able to understand where would the Username and Password be required in the request. This is a code snippet. If anyone can tell where I need to authenticate the Username and Password in this code snippet to fetch the JSON Object, it would be very helpful.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.wtf(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.wtf(error.getMessage(), "utf-8");
}
});
queue.add(jsonObjectRequest)
This is how you can use POST Method in volley:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject object = new JSONObject(response);
// here is your json object
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// volley errors
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(stringRequest);
Create a jsonObject with username and password then pass this object to the JsonObjectRequest
Your code will be like this :
JSONObject body= new JSONObject();
body.put("username", "user");
body.put("password", "userPassword");
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url,
body, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.wtf(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.wtf(error.getMessage(), "utf-8");
}
});
queue.add(jsonObjectRequest)
You need to understand what is form-data and how it is used:
Definition and Usage
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute).
The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with method="post").
Notes on GET:
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user wants to bookmark the result
GET is better for non-secure data, like query strings in Google
Notes on POST:
Appends form-data inside the body of the HTTP request (data is not shown in URL)
Has no size limitations
To pass username and password arguments as form-data you can create StringRequest and override it's getParams method to return a map of data.
StringRequest request = new StringRequest(
Request.Method.POST,
requestUrl,
onResultListener,
onErrorListener) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("username", username)
hashMap.put("password", password)
return hashMap;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// You can parse response here and throw exceptions when required.
return super.parseNetworkResponse(response);
}
};
queue.add(request)

Volley bad URL - how to fix that?

I'm having a problem with java volley when I click login
private void Login(){
String url = "api.matraindonesia.com/login";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("success")){
Toast.makeText(getApplicationContext(),"Login Successfully!",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"Login Failed!",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"this error:"+ error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email",etEmail.getText().toString().trim());
params.put("password",etPassword.getText().toString().trim());
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
com.android.volley.VolleyError: java.lang.RuntimeException: Bad URL
you need to use http:// or https:// at the beginning or the url
String url = "http://api.matraindonesia.com/login";
or if your server is on SSL
String url = "https://api.matraindonesia.com/login";
Edit (after your comment) :
typically MethodNotAllowedHttpException happen when, route method is not match.
Suppose you define POST request route file, but you sending GET Request to the route.

Android Volley request failing while making a call to wit.ai API

I'm trying to use the speech recognition REST API service from wit.ai
I have used Volley to send a POST request to the URL
https://api.wit.ai/speech
This is what I have currently done:
void makeApiCall(){
StringRequest request = new StringRequest(Request.Method.POST, "https://api.wit.ai/speech", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("wit_response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("wit_response",error.toString());
}
}){
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> params = new HashMap<>();
params.put("Authorization","Bearer XXXXXX"); //hidden my token
params.put("Content-Type","audio/mpeg3");
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
return sendToByte();
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
}
I am receiving an error of com.android.volley.ClientError on the wit_response log key inside onErrorResponse() method
I have not missed the content type and authorization header, and my sendToByte function is succesfully returning an mp3 file converted to byte array.
What is the issue?
I had to use this link https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
And use MultiPartRequest class as described in this to upload my file.
Please comment here if you need any assistance (for all future folks)

Empty Response Received on Android POST Request

I'm using Volley to perform rest requests on android. When I make a login attempt it fails to give the response and instead returns an empty response.
The server side works fine, I have received the empty response on Android client side.
This is the code I wrote:
HashMap<String, String> params = new HashMap<String, String>();
params.put("email", "nifras.personal#gmail.com");
params.put("password", "123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(getApplicationContext(),
response.toString(),
Toast.LENGTH_LONG).show();
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
Try Using Map and Object (I use that for String too) like this:
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("param1", getParam1());
jsonParams.put("param2", getParam2());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
// ...... you know the rest
btw, 400 is usually bad request (if my memory serves me correctly), so I would print the JSON object before sending it, and see if it's exactly what server is expecting, you can use Postman to check it too, might be easier (REST client version of Postman in chrome is more comfortable to use).
a quick and dirty way to print it:
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("param1", getParam1());
jsonParams.put("param2", getParam2());
Log.d("My JSON Object",(new JSONObject(jsonParams)).toString());
Hope This Helps.
The correct Answer for this question is shown below. In this version of the request, the Post parameters are overriden in the existing getParams() method of Volley. The mistake I did was to not override that method.
String url = "http://httpbin.org/post";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
String site = jsonResponse.getString("site"),
network = jsonResponse.getString("network");
System.out.println("Site: "+site+"\nNetwork: "+network);
} catch (JSONException 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<>();
// the POST parameters:
params.put("site", "code");
params.put("network", "tutsplus");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
Use this for solve your problem
ArrayList<NameValuePair> arrResult = new ArrayList<NameValuePair>();
arrSchoolResult.add(new BasicNameValuePair("email", ""nifras.personal#gmail.com""));

Android Volley POST string in body

I'm trying to use Volley library to communicate with my RESTful API.
I have to POST string in the body, when I'm asking for the bearer Token. String should look like this:
grant_type=password&username=Alice&password=password123
And header:
Content-Type: application/x-www-form-urlencoded
More info about WebApi Individual Accounts:
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
Unfortunately I can't figure out how can I solve it..
I'm trying something like this:
StringRequest req = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "User0");
params.put("password", "Password0");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
I'm getting 400 Bad Request all the time.
I think that I'm actually sending request like this:
grant_type:password, username:User0, password:Password0
instead of:
grant_type=password&username=Alice&password=password123
I would be very grateful if anyone has any ideas or an advice..
To send a normal POST request (no JSON) with parameters like username and password, you'd usually override getParams() and pass a Map of parameters:
public void HttpPOSTRequestWithParameters() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
// volley will escape this for you
params.put("randomFieldFilledWithAwkwardCharacters", "{{%stuffToBe Escaped/");
params.put("username", "Alice");
params.put("password", "password123");
return params;
}
};
queue.add(postRequest);
}
And to send an arbitary string as POST body data in a Volley StringRequest, you override getBody()
public void HttpPOSTRequestWithArbitaryStringBody() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="grant_type=password&username=Alice&password=password123";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}
};
queue.add(postRequest);
}
As an aside, Volley documentation is non-existent and quality of StackOverflow answers is pretty bad. Can't believe an answer with an example like this wasn't here already.
First thing, I advise you to see exactly what you're sending by either printing to the log or using a network sniffer like wireshark or fiddler.
How about trying to put the params in the body? If you still want a StringRequest you'll need to extend it and override the getBody() method (similarly to JsonObjectRequest)
I know this is old, but I ran into this same problem and there is a much cleaner solution imo found here: How to send a POST request using volley with string body?

Categories

Resources