How to get restaurant menus from Locu API - android

I have looked at several APIs for acquiring restaurant menu for a particular location and determined that Locu API works best for me.
I was trying the basic example listed on locu website:
curl -X POST https://api.locu.com/v2/venue/search/ -d '{"fields":["name","menu_items","location","categories","description"],"menu_item_queries":[{"price":{"$lt":6},"name":"burrito"}],"venue_queries":[{"location":{"locality":"San Francisco"}}],"api_key":"MY_API_KEY"}'
Where, MY_API_KEY is the API_KEY that I received when I signed up.
As long as I include "menu_items" parameter, I keep getting the response:
{"status": "error", "http_status": 400, "error": "The requested \"menu_items\" field is either invalid or your account does not have permissions to access it."}
I did not come across any documentation regarding what I need to do in order to get the permissions for querying "menu_items". If anyone could point me in the right direction, I will really appreciate that.
I have already gone through some relatively old questions on here and they did not address this particular issue.
Also, there doesn't seem to be a tag for Locu api here. I am going to try and tag the question with some generic tags. Please excuse me for that.

I know this is an old question, but I've found that the solution is to request the "menus" field in a venue search. The API will return the "menu_items" as sub-objects of the menus.

`
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try{
String result;
URL url = new URL("https://api.locu.com/v1_0/venue/search/?api_key=" +apiKey);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);}
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}`

Related

To connect with a web-service there is two options, either use a Library or "JSONParser" Class. Which is better? which one is safe? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am asking this because I am beginner in android development.
I am doing a core-banking application, so I used JSON Parser class to connect with REST Web-Service,
JSONParser Class is,
package com.anvinsolutions.digicob_custmate;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;// = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder(); // add this line
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
and i am confused if this method have any problem with Security,performance?
i didn't try any Libraries till now, i just used this JSONParaser Class. i think its easy to work with a JSONParser Class..
WHICH ONE TO USE?
thank you in advance! ;)
You never use JSonParser class to connect to a Web service. From your code, looks like you are using Vanilla HttpURLConnection class for connecting to service and using the JSonParser class to parse the result which is good and simple if you only have a couple of web requests to make in your application.
However since you said, it's banking application, you might have to think about scalability, multiple requests and stuffs like that. You could well try to handle them by yourself but the suggested way would be to use one of the tried and tested network libraries available for Android. Retrofit and Volley are two such and there are many more. The choice of the library to use is based on your use cases.
#AJay has already pointed to a page for comparison. Have a look.
Onto your next thing, about the parsing, performance is one of the key factors. Have a look at the below link for the options you have - http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
I would say GSon is pretty good among all. We use it extensively in our in-house products.
You can use GsonParser by Google.https://github.com/google/gson
Hello you can use any of these 3 libraries they both are equally good in performance. Check this link, it will help you. Happy learning.
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
If you have a deal with REST service, the easiest way is to use Retrofit library: https://square.github.io/retrofit/
With Retrofit you do not need to implement http calls and it automatically parses/creates json.
If you need more flexibility, I suggest using OkHttp library http://square.github.io/okhttp/, which is much simpler than pure HttpUrlConnection in combination with Gson lib https://github.com/google/gson for json parsing/creating.

Sending a form with GET to an URL

I have a simple form and i need to send it to a URL with the parameters.
Let's say I have one parameter called token and I want to send it to example.com/?token=the_token
I don't need to handle or get the output, just send it to this url.
How I can do this? I've been trying for hours to use URLCONNECTION and HTTPURLCONNECTION and nothing worked.
Since I tried many things and nothing worked, I am trying from scratch.
This is it:
if (token.isEmpty()) {
getGCMToken();
} else {
//Send the token to example.com/?token=token. The URL will add the token to my database with PHP.
}
Please do not reply with DefaultHttpClient. It is deprecated.
Trying URLConnection():
if (token.isEmpty()) {
getGCMToken();
} else {
//Send the tokeb to example.com/?token=token
URLConnection connection = null;
try {
connection = new URL("mysite.com/send.php?id=my_id").openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setRequestProperty("Accept-Charset", "UTF-8");
try {
InputStream response = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
Look, I built a whole web/http communications class last year. I'm copying you the chunk which deals with get(s):
Import at least the following:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
try{
String mainUrl = "<your_url>";
String query = "?" + "<add_your_params_here>";
URL url = new URL (mainUrl + query);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// If you want to process the response you have to do something the the in InputStream. But ommiting it here, as you said you won't use the response.
}
catch (FileNotFoundException fnf){
Log.e("Incorrect Url", "Resource was not found");
}
catch (Exception e){
}
And remember to add the INTERNET permission for your Android Manifest xml file: android.permission.INTERNET
Check this response for adding internet permissions: What permission do I need to access Internet from an android application?
Use URLConnection for this.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();

Json call making in android

I am new bee in Android , so the knowledge regarding android is not so vast.
I am trying to implement Json call in android and i am using the foolowing code to get the list of all the contacts in the database.
package com.example.library;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class SecondActivity extends Activity {
Button show_data;
JSONObject my_json_obj;
String path,firstname,lastname;
{
path = "http://192.168.71.129:3000/contacts";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpEntity entity;
HttpResponse response = null;
HttpURLConnection urlconn;
my_json_obj = new JSONObject();
}
}
I dont know if this is the right method but this code was already existing in another project and i have just made some change.
Please guide me through this one as i have gone through many stackoverflow and google answers,but it is very confusing as i am just a beginner and dont have knowledge of json calls in android.
I could give you a chunk of code and say "Hey try this", but like you stated that you are very new to Android so I simply wont.
I think its of more value that you can learn something beter by trying then simply copy pasting code(most of the time)
There are a couple of things you need to consider when you do network request and parsing data.
Network request you must always do this in a seperate thread then the UI thread, because if you dont youll get a NetworkOnMainUiThreadException if I am correct out the top of my head.
The same applies for parsing the data you have retrieved from your request.
I dont see any parsing of data in your current code but I just wanted to give you a headsup because you will prob do this at some point in your application.
Here you can find a tutorial how to do threading with the AsyncTask. this is "the way" how it should be done in Android, they realy made it easy for you.
When reading that tutorial you will get the basic knowlage to do stuff in this class.
When you get the concept of threading and how to work with this newly added skill I would suggest reading and following up on this json tutorial here.
I hope this helps
try this, result variable has your responce
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("paset_your_url_here");
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
Log.i("", "-----------------------"+result);
} catch(Exception e) {
e.printStackTrace();
}finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if you want to prase json then first do googling and if you get your answer by this then vote up :)

Error with using HttpPost on Android

I am trying to input text from Android into websites, and I read that httppost is a good option. I download the HttpClient 4.2.2 (GA) tar.gz, unzipped them, and copied the 7 jars into the lib folder of my android project in Eclipse. I'm pretty sure I got all the jars, since they matched those listed on the website.
I then proceeded to copy and paste the top tutorial from: http://hc.apache.org/httpcomponents-client-ga/quickstart.html
I imported everything, and was left with this error:
EntityUtils.consume(entity1); //X
} finally {
httpGet.releaseConnection(); //X
This portion of code is at two places in the tutorial, and errors occur at both.
Eclipse says for the first line:
"The method consume(HttpEntity) is undefined for the type EntityUtils."
Second line:
"The method releaseConnection() is undefined for the type HttpGet."
I'm pretty sure I downloaded every jar, transported them correctly, and imported everything. What is making the error? Thanks.
Here is what I have now. Edward, I used some of the code from your methods, but just put them into onCreate. However, this isn't working. A few seconds after I go from the previous activity to this one, I get the message that the app "has stopped unexpectedly".
I have a question about inputting my Strings into the website text fields: Do I use NameValuePairs of HttpParams? Here's my code, can you see what's wrong? Thanks.
package com.example.myapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class BalanceCheckerActivity extends Activity {
private final String LOGIN_URL = "https://someloginsite.com"; //username and password
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance_checker);
String username = getIntent().getExtras().getString("username");
String password = getIntent().getExtras().getString("password");
//Building post parameters, key and value pair
List<NameValuePair> accountInfo = new ArrayList<NameValuePair>(2);
accountInfo.add(new BasicNameValuePair("inputEnterpriseId", username));
accountInfo.add(new BasicNameValuePair("password", password));
//Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
//Creating HTTP Post
HttpPost httpPost = new HttpPost(LOGIN_URL);
BasicHttpParams params = new BasicHttpParams();
params.setParameter("inputEnterpriseID", username);
params.setParameter("password", password);
httpPost.setParams(params);
//Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(accountInfo));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
HttpResponse response = null;
InputStreamReader iSR = null;
String source = null;
// Making HTTP Request
try {
response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
iSR = new InputStreamReader(response.getEntity().getContent());
BufferedReader br = new BufferedReader(iSR);
source = "";
while((source = br.readLine()) != null)
{
source += br.readLine();
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
System.out.println(source);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_balance_checker, menu);
return true;
}
}
That mostly looks pretty good to me. I only saw one obviously wrong piece of code in it:
while((source = br.readLine()) != null)
{
source += br.readLine();
}
That's kind of a mess, and rather than try to untangle it, I'll just rewrite it.
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
String source = sb.toString();
Also, you shouldn't be doing network I/O from onCreate() or even from within your UI thread, since it can block for a long time, freezing your entire UI and possibly causing an "Application Not Responding" (ANR) crash. But for a simple test program, you can let that slide for now. For production code, you'd launch a thread or use AsyncTask().
Anyway, we're not really interested in building and debugging your program for you. Have you tried this code out? What was the result?
One final note: a login sequence like this is likely to return an authentication token in the form of a cookie. I forget how you extract cookies from an HttpResponse, but you'll want to do that, and then include any received cookies as part of any subsequent requests to that web site.
Original answer:
I think you've gotten yourself all tangled up. The Apache http client package is built into Android, so there's no need to download any jar files from apache.
I'm not familiar with EntityUtils, but whatever it is, if you can avoid using it, I would do so. Try to stick with the bundled API whenever possible; every third-party or utility library you add to your application increases bloat, and on mobile devices, you want to keep your application as light as possible. As for the actual "consume()" method not being found, that's probably a mistake in the documentation. They probably meant consumeContent().
The releaseConnection() call is probably only necessary for persistent connection. That's relatively advanced usage; I don't even do persistent or managed connections in my own code.
You haven't provided enough information to let us know what it is you're trying to do, but I'll try give you a reasonably generic answer.
There are many, many ways to transmit data to a server over the http protocol, but in the vast majority of cases you want to transmit form-encoded data via HttpPost.
The procedure is:
Create a DefaultHttpClient
Create an HttpPost request
Add headers as needed with setHeader() or addHeader().
Add the data to be transmitted in the form of an HttpEntity
Call client.execute() with the post request
Wait for and receive an HttpResponse; examine it for status code.
If you're expecting data back from the server, use response.getEntity()
There are many HttpEntity classes, which collect their data and transmit it to the server each in their own way. Assuming you're transmitting form-encoded data, then UrlEncodedFormEntity is the one you want. This entity takes a list of NameValuePair objects which it formats properly for form-encoded data and transmits it.
Here is some code I've written to do this; these are only code fragments so I'll leave it to you to incorporate them into your application and debug them yourself.
/**
* POST the given url, providing the given list of NameValuePairs
* #param url destination url
* #param data data, as a list of name/value pairs
*/
public HttpResponse post(String url, List<NameValuePair> data) {
HttpPost req = new HttpPost(url);
UrlEncodedFormEntity e;
try {
e = new UrlEncodedFormEntity(data, "UTF-8");
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "Unknown exception: " + e1);
return null; // Or throw an exception, it's up to you
}
return post(req, e);
}
/**
* Post an arbitrary entity.
* #param req HttpPost
* #param data Any HttpEntity subclass
* #return HttpResponse from server
*/
public HttpResponse post(HttpPost req, HttpEntity data) {
try {
HttpClient client = new DefaultHttpClient();
req.setEntity(data);
HttpResponse resp = client.execute(req);
int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
Log.w(TAG,
"http error: " + resp.getStatusLine().getReasonPhrase());
return null; // Or throw an exception, it's up to you
}
return resp;
} catch (ClientProtocolException e) {
Log.e(TAG, "Protocol exception: " + e);
return null;
} catch (UnknownHostException e) {
return null;
} catch (IOException e) {
Log.e(TAG, "IO exception: " + e);
return null;
} catch (Exception e) {
// Catch-all
Log.e(TAG, "Unknown exception: " + e);
return null;
}
}

Replacement for deprecated Google web search API for Android

I'm looking to search Google from my Android app and return results. Everything I've found points towards the Google Web Search API which the page now says is deprecated and is being replaced by a Custom Search API.
The new custom search API only allows you to search through websites you've created a custom search engine for. I want to search all of the internet as anyone would through Google.
How can I do this?
Android has a lot of search capabilities - all built-in.
Look here:
http://developer.android.com/guide/topics/search/index.html
Google Code and the Android SDK are two different things. The Web Search API is Google Code and, and you noted, it has indeed been deprecated in favor of Google Custom Search:
http://code.google.com/apis/customsearch/v1/overview.html
http://www.google.com/cse/
Finally, here's a good blog entry that shows you how to invoke a Bing/Yahoo! web search from Android:
http://www.codexperiments.com/java/2011/01/create-your-own-web-search-application/
Frankly, the Bing API looks a heck of a lot better than Google Custom Search. Starting with the fact that Bing's API doesn't limit you to 100 queries/day like Custom Search does :)
'Hope that helps!
You can Bing search API -
First you need to create an account at Microsoft and get an account key, then use it as follows:
import android.os.AsyncTask;
import android.util.Log;
import org.apache.commons.codec.binary.Base64;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by Asaf on 08/06/2014.
*/
public class SearchAsyncTask extends AsyncTask<Void, Void, Void> {
private final String TAG = getClass().getName();
#Override
protected Void doInBackground(Void... params) {
try {
String bingUrl = "https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27pinhassi%27";
String accountKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url = null;
url = new URL(bingUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
InputStream response = urlConnection.getInputStream();
String res = readStream(response);
Log.d(TAG, res);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
return null;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
//System.out.println(line);
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}

Categories

Resources