How to make GET request to Yelp api using volley? - java

I am using Volley to make get request to Yelp Api and keep getting "BasicNetwork.performRequest: Unexpected response code 400 for https://api.yelp.com/v3/businesses/search" error. I made GET request on Postman using the same parameters and headers and it worked just fine. Yelp has released their new API v3 recently,so I did not find any useful similar problem on stackoverflow.
StringRequest stringrequest = new StringRequest(Request.Method.GET,
"https://api.yelp.com/v3/businesses/search",
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
progressDialog.hide();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
//headers.put("Content-Type","application/x-www-form-urlencoded");
headers.put("Authorization",[Bearer myToken]);
return headers;
}
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("latitude",latitude);
params.put("longitude",longitude);
params.put("radius","15");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringrequest);

Related

why does the JSON response imperfect in Volley Android?

My complete response in Postman is the following but I can't get a complete response as JSON when using Volley android.
My volley code :
I have no problem sending a request but I show my logic that maybe was a problem with my code.
public void makeAssignment(final String token, HashMap<String,String> info_doc , List<Region> result, final OnMakeAssignment onMakeAssignment) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("document_type", info_doc.get("type_doc"));
params.put("title", info_doc.get("title_doc"));
params.put("meter", info_doc.get("meter_doc"));
params.put("price", info_doc.get("price_frosh"));
params.put("mortgage_price", info_doc.get("vagozari_price_rahn")); // رهن
params.put("monthly_rent_price", info_doc.get("vagozari_price_ejareh")); // ejareh
params.put("address", info_doc.get("address"));
params.put("description", info_doc.get("vagozari_description"));
params.put("region[0]", "1");
if (result.isEmpty()){
params.put("region[0]", "all");
}else{
for (int i = 0; i < result.size(); i++) {
params.put("region["+i+"]", String.valueOf(result.get(i).getId()));
}
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, Vars.MAKE_ASSIGNMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
onMakeAssignment.onReceived(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError) {
context.startActivity(new Intent(context, NoInternet.class));
onMakeAssignment.onError(error.getMessage());
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
// params.put(Vars.KEY_AUTH, Vars.AUTH);
params.put(Vars.KEY_AUTH, token);
params.put(Vars.KEY_USERNAME, Vars.USERNAME);
params.put(Vars.KEY_PASSWORD, Vars.PASSWORD);
return params;
}
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
The JSON response details are imperfect when I call this method with the Volley library but a response in the Postman is complete. so finally o don't know why this happens because it isn't a problem in requests when using PostMan. so my android Logcat gets back this response when running a method request but unfortunately it isn't the same as the response Postman.
I/resewssssssss: {"clients":[{"id":44,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic LUnrhilQIWfdY6YQr6lxWCuZ8TAtNs4ailckURW6MG","client_type":1,"created_at":"2020-07-22T12:27:41.000000Z","updated_at":"2020-07-22T12:27:41.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":6,"client_regions":[{"id":69,"client_id":44,"region_id":1}]},{"id":43,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic jwfz4Ll1YYE3oG4ZFDtAQEgufW4q2ZozEr3LUJU0q58","client_type":1,"created_at":"2020-07-22T11:59:49.000000Z","updated_at":"2020-07-22T11:59:49.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":2,"client_regions":[{"id":68,"client_id":43,"region_id":1}]},{"id":31,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic SI3FWNH1mxg8N4JL0HEu45nEqlUBtEv
JQbRdmpuR4CeKcJ0","client_type":1,"created_at":"2020-07-20T16:01:48.000000Z","updated_at":"2020-07-20T16:01:48.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":1,"client_regions":[{"id":51,"client_id":31,"region_id":1}]},{"id":33,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic nOwhIwlowhqgQUXEHH8heXSmM
iJOqNEoJiVb6TKwO381Yp","client_type":1,"created_at":"2020-07-20T20:05:22.000000Z","updated_at":"2020-07-20T20:05:22.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":1,"client_regions":[{"id":53,"client_id":33,"region_id":1},{"id":54,"client_id":33,"region_id":118}]},{"id":34,"name":null,"mobile":"09123456789","mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic DkCrb8tzrt5FKldXon0xm8d
e2fLpugea61lVRnOR3IATSfb","client_type":1,"created_at":"2020-07-20T20:51:55.000000Z","updated_at":"2020-07-21T18:08:46.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":1,"client_regions":[{"id":55,"client_id":34,"region_id":1}]},{"id":1,"name":"\u06a9\u0627\u0631\u0628\u0631 \u062a\u0633\u062a","mobile":null,"mobile_confirmed":0,"invited":0,"device_id":null,"firebase_token":null,"device_serial":null,"credit":"0","city_id":1,"region_id":null,"state_id":1,"api_token":"Basic a142pbR0LGvfaZFi6333ZIj5pghgyzsFmGiNvn4k4CwzRi6g","client_type":1,"created_at":"2020-07-02T13:16:26.000000Z","updated_at":"2021-05-21T02:48:02.000000Z","credit_date":"2021-05-18","description":"ttewtwt","assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":0,"client_regions":[{"id":1,"client_id":1,"region_id":1},{"id":2,"client_id":1,"region_id":2},{"id":3,"client_id":1,"region_id":3}]},{"id":9,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token"

API returning error: "field cannot be empty"

I am currently trying to interface with the Tidal API and i'm having some trouble. Here is my code, I am using the Volley Library:
JSONObject pload = new JSONObject();
try {
pload.put("username", username);
pload.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, ENDPOINT, pload, response->{
Gson gson = new Gson();
JSONArray data = response.optJSONArray("data");
Log.d("RESPONSE", response.toString());
}, error -> {
String responseBody = null;
try {
responseBody = new String(error.networkResponse.data, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("ERROR", responseBody);
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("X-Tidal-Token", "q--------------------------k");
headers.put("Content-Type", "application/json");
return headers;
}
};
mqueue.add(request);
The LogCat:
D/REQUEST: body: {"username":"b-------#gmail.com","password":"p------"} ___ headers: {X-Tidal-Token=q---------------k, Content-Type=application/json} ___ request.tostring: [ ] https://api.tidalhifi.com/v1/login/username 0xcc20303d NORMAL null
E/Volley: [309] BasicNetwork.performRequest: Unexpected response code 400 for https://api.tidalhifi.com/v1/login/username
D/ERROR: {"status":400,"subStatus":1002,"userMessage":"password cannot be blank,username cannot be blank"}
As you can see the payload is not empty so i'm a bit confused. Tidal doesn't have an official API but there are some unofficial wrappers I have been using for reference, here are a few examples of used code:
Javascript:
request({
method: 'POST',
uri: '/login/username?token=kgsOOmYk3zShYrNP',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
username: authInfo.username,
password: authInfo.password,
}
Java:
var url = baseUrl.newBuilder()
.addPathSegment("login")
.addPathSegment("username")
.build();
var body = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
var req = new Request.Builder()
.url(url)
.post(body)
.header(TOKEN_HEADER, token)
.build();
Java again:
HttpResponse<JsonNode> jsonResponse = restHelper.executeRequest(Unirest.post(API_URL + "login/username")
.header("X-Tidal-Token", "wdgaB1CilGA-S_s2")
.field("username", username)
.field("password", password));
If needed I can post the links to all the wrappers and provide a tidal token for testing (It's fairly easy to acquire you just need to sniff a packet from the tidal desktop app) . I've tried overriding getParams() but that didn't work. Any help is appreciated!
You're using the wrong format to send the request, You're using Json when you need a Url encoded format, the link for reference: Send form-urlencoded parameters in post request android volley
One Solution: A string request:
final String api = "http://api.url";
final StringRequest stringReq = new StringRequest(Request.Method.POST, api, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
//do other things with the received JSONObject
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Username", "usr");
pars.put("Password", "passwd");
pars.put("grant_type", "password");
return pars;
}
};
//add to the request queue
requestqueue.AddToRequestQueue(stringReq);

How do you obtain a Auth token using webView in android?

I need to receive the token on my Android aplication..
I created and API on laravel, and i need to receive a token, but i dont know how to do it on android.
It would be difficult to read a token into a WebView and then try to extract it from the WebView. Typically, you just make an HTTP Request to an API method to get the token, then store the token for later use. Here is an example of doing that, which doesn't involve using the WebView:
// You need a URL to an API method that will return the token
if (apiToken.length() == 0) {
getToken("https://mycompany.com/account-services/api/v1/token");
}
private void getToken(String url) {
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Response JSON contains the token
JSONObject obj = new JSONObject(response);
apiToken = obj.getString("access_token");
// Save the token in the shared appPrefs so it can be referenced in other classes
SharedPreferences appPrefs = getSharedPreferences("appPreferences",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = appPrefs.edit();
prefsEditor.putString("apiToken", apiToken);
prefsEditor.commit();
} catch (JSONException e) {
Log.e("myapp", "JSONException Error: " + e.getLocalizedMessage());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("myapp", "Response Error: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams()
{
// Most Token API methods have their own secret user id and password
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "apiusername");
params.put("password", "apipassword");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
// This API expects the parameters in the form of "grant_type=password&username=apiusername&password=apipassword"
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};
// the Request Queue has been declared in the Application object on app startup
MyApplication.getInstance().addToRequestQueue(postRequest);
}

Android post request with non key pair

Below is my currently working code to switch on a light with my home automation system. I am upgrading to a new system and it needs a modified post command. Currently I think this sends the key pair "lightswitch1=ON". I need it to only send "ON" but I am not sure how to do this. Below is the CURL command that works.
public void turnonlight() {
String url = "http://example.com:8090/CMD";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(MjpegActivity.this,response,Toast.LENGTH_LONG).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
},
new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MjpegActivity.this,error.toString(),Toast.LENGTH_LONG).show();
//This code is executed if there is an error.
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put(lightswitch1 "ON"); //Add the data you'd like to send to the server.
return MyData;
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
MyRequestQueue.add(MyStringRequest);
}
curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "ON" "http://example.com:8090/CMD"
The following should be working with Volley :
String url = "http://example.com:8090/CMD";
StringRequest myStringRequest = 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) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
#Override
public String getBodyContentType() {
return "text/plain";
}
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "ON";
return httpPostBody.getBytes();
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
myStringRequest.setShouldCache(false);
MyRequestQueue.add(myStringRequest);
The body is overriden by getBody() and the specified header with getHeaders().

HTTP-Headers not included in request made with Volley

I have the below request but for some reason the headers aren't being "attached" to the request? Please could you maybe assist me with this?
public void get(String servicesUrl, String end_tag_url) {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url + servicesUrl + end_tag_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("header1", "value");
params.put("header2", "value");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
I get connection to the server but the is an auth failure because the headers aren't being implemented in the connection.
I have tested on a Chrome add-on called Advanced-Rest-Client and added the headers which worked.
I could add 2 of the headers to the URL but the 3rd one cannot be attached to the URL and needs to be a header?
When creating a request, override getHeaders(), like so:
new JsonObjectRequest(url, jsonRequest, listener, errorListener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> map = new HashMap<String, String>();
map.put("X-REST-API-Key", resources.getString(R.string.parse_api_key));
map.put("X-Application-id",
resources.getString(R.string.application_id));
if (sessionToken != null) {
map.put("X-Session-Token", sessionToken);
}
return map;
}
};

Categories