CSE (Custom Search Engine) steps - android

EDIT
...I'm still wondering why I can't find a solution to this issue.
I verify the API Key and the Custom Search Engine ID.
May be I left some library?
I have (related to the question):
-GWT SDK
-validation-api
I'm still reading posts and documentation....but nothing works....
ORIGINAL
I'm trying to develop an Android app. using CSE (Custom Search Engine). I've read a lot about this issue (here and in everywhere), but right now I'n not sure about anything: it's a mess for me.
I would like to know if I'm in the right way.
I get the API access key and the CSE ID
I want to use my own CSE, so I have to open a connection using "https://www.googleapis.com/customsearch/v1?key=_MY_API_KEY_&cx=_MY_SEARCH_ENGINE_ID&q=_MY_QUERY_
Here is the piece of code:
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=_MY_KEY_&cx=_MY_ID_&q=tomcat");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
I get an SSL exception at
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
javax.net.ssl.SSLException: Connection closed by peer.
I don't know how I could fix this error, because all the examples I found related to CSE have (more or less) the same code to connect to the custom url search.
This is my first time here, so I not sure if I've expressed myself in the proper way.
Thanks a lot in advance.
Isaac.

I think you are trying to access a secure url (https) while using HttpURLConnection (instead HttpsURLConnection, mind the 's'), therefore the ssl error. Change to secure call and see if it worked.
To check if the engine is working as intended, just paste the url you mentioned ("https://www.googleapis.com/customsearch/v1?key=_MY_API_KEY_&cx=_MY_SEARCH_ENGINE_ID&q=_MY_QUERY_") in the browser - if it works, the engine is alright and the problem is in your code.

Related

Spotify Android - Make Authorized Web Requests

I'm working on an Android app that implements the Spotify API to allow the users to listen to music. I've configured the Player that Spotify has created for android devices, but it's incredibly limited in terms of its functionality, so I've had to go through Spotify's Web API to do more advanced features.
I've hit a bug when trying to get a list of the user's own playlists. I'm making a request using:
URL url = new URL("https://api.spotify.com/v1/me/playlists");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
But instead of this command going through like it does for the other web API requests I've made, it throws the error:
java.io.FileNotFoundException: https://api.spotify.com/v1/me/playlists
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:242)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
at com.tmacstudios.spotifyvoice.WebWrapper$override.searchUserPlaylist(WebWrapper.java:257)
at com.tmacstudios.spotifyvoice.WebWrapper$override.access$dispatch(WebWrapper.java)
at com.tmacstudios.spotifyvoice.WebWrapper.searchUserPlaylist(WebWrapper.java:0)
at com.tmacstudios.spotifyvoice.MainActivity$6.run(MainActivity.java:382)
at java.lang.Thread.run(Thread.java:818)
I'm not entirely sure why I'm getting this error, but I think it may have to do with not having the necessary authorization to make this request. Can anyone please help me solve this problem?
After studying the documentation some more, I was able to figure out a way to solve my problem. I was in fact getting the error since I wasn't using the proper authorization.
You can get the authorization token in OnActivityResult using this code:
AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
if (response.getType() == AuthenticationResponse.Type.TOKEN) {
authToken = response.getAccessToken();
Log.e("MainActivity","Auth Token: "+authToken.toString());
...
Then when making the URL request, just pass in the authorization token as a header.
URL url = new URL("https://api.spotify.com/v1/me/playlists");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", "Bearer " + authToken);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
...
Also note that you must have the permissions you are using enabled as scopes when you are forming the authorization request initially.

Sending POST request from android to RoR app, but cannot find the right URL

I am not able to reach the create Method in tests_controller.rb with this code.
String newUrl = "http://10.0.2.2:3000/tests";
httpcon = (HttpURLConnection) ((new URL(newUrl).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
And here is my routes.rb (I use model scaffold to create the RoR app).
resources :tests
Am i wrong in routing or something. When i run this code in Android, the create method is not run at all.
It's hard to tell the reason for the failure you have. Your routes seem OK. You can check couple other things:
Is your Rails server listening on the right interface and port?
Is there any network problem between the machine your client is working on and the server?
Instead of going through the cycle of edit-compile-deploy-run of Android, simply use curl or a similar tool to try the POST request from the console.
When you pinpoint the place of the problem, then you can ask another question, or, more likely, already find the answer online.

Android connect to Mysql database tutorial

Does anybody know a complete and working tutorial about how to retrieve data from MYSQL and display it in Android? I'm asking this because all the tutorials I found are older than API 22 and from API 22 the HttpClient is deprecated. And I'm a new Android Developer so I can't write any code on my own. :)
HttpClient
Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.
This interface was deprecated in API level 22.
Please use openConnection() instead.
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.
Please visit this webpage for further details.
http://android-developers.blogspot.in/2011/09/androids-http-clients.html
An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.
Uses of this class follow a pattern:
Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
For example, to retrieve the webpage at http://www.android.com/:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
Please visit this webpage for further details.
http://developer.android.com/reference/java/net/HttpURLConnection.html
urlconnection tutorials, can visit this websites
+http://www.vogella.com/tutorials/AndroidNetworking/article.html
+http://javatechig.com/android/android-networking-tutorial

Right way to manage HTTP connection in Android

I have written two programs which handle the HTTP request. I wanted to know if one is better than other -
Program 1 (Using HttpURLConnection)
URL url = new URL("https://www.google.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(false);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
Program 2 (Using HttpPost)
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://test.com");
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
Also in program 2, I use a singleton to get the connection object. But in program 1 there is no global connection object and I need to recreate the HttpURLConnection object everytime I make a request. Please let me know if I am on the right track.
Thank You
I would like to suggest you to use Android Asynchronous Http Client library.
Then you can avoid these basic stuffs. The one things I like most is HTTP requests happen outside the UI thread.
Also in program 2, I use a singleton to get the connection object. But in program 1 there is no global connection object and I need to recreate the HttpURLConnection object everytime I make a request.
Method 2 looks like simpler, but it's so old :
Apache HTTP Client - HTTPPost
DefaultHttpClient and its sibling AndroidHttpClient are extensible
HTTP clients suitable for web browsers. They have large and flexible
APIs. Their implementation is stable and they have few bugs. But the
large size of this API makes it difficult for us to improve it without
breaking compatibility. The Android team is not actively working on
Apache HTTP Client.
HttpURLConnection
HttpURLConnection is a general-purpose, lightweight HTTP client
suitable for most applications. This class has humble beginnings, but
its focused API has made it easy for us to improve steadily.
Prior to Froyo, HttpURLConnection had some frustrating bugs.
We should choose method 1 when :
For Gingerbread and better, HttpURLConnection is the best choice. Its
simple API and small size makes it great fit for Android. Transparent
compression and response caching reduce network use, improve speed and
save battery. New applications should use HttpURLConnection; it is
where we will be spending our energy going forward.
And method 2 when :
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
Thanks,

FileNotfoundException when trying to checkin Foursquare using Android

I tried looking for answers for this since last few days with no luck, Even some of the stackoverflow answers did not help.
I am trying to checkin a user after receiving his UserToken via Android. I get a FileNotfoundException at getInputStream(), non authenticated APIs like
"https://api.foursquare.com/v2/venues/categories" work well. Am i missing something?
URL url = new URL("https://api.foursquare.com/v2/checkins/add?oauth_token="+token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("venueId","12238");
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setAllowUserInteraction(true);
conn.connect();
InputStream is = conn.getInputStream();
String response = streamToString(is);
return response;
Managed to solve this after lot of effort. See my answer below.
Try adding the oauth_token using the same method you use to add the venueid. Also, your venueid is invalid, so make sure you are checking the user in to a real venue.
The HttpURLConnection class is misleading in that it will throw a FileNotFoundException for any HTTP error code of 400 or above.
So it's not necessarily an incorrect URL (404) it could be 400 (bad request), 403 (forbidden), 500 (internal server error) etc.
Use the getResponseCode method to get a more precise indication of the problem.
first: Yoy have https url, and trying to create HttpURLConnection. You should use HttpsURLConnection.
Second: You can try to add conn.setDoOutput(true), "post" request requires it. And without it server can try give a get request from you despite on conn.setRequestMethod("POST"). Also you can check headers from your browser plugin, and put them into your request.
Okie I finally managed to solve the problem, I don't know what exactly was the problem with my code above but the following worked.
This API requires a POST call but even the venueID must be part of the URL and addRequestProperty does not seem to be sending the venueID properly. Hence I changed the code to
URL url = new URL("https://api.foursquare.com/v2/checkins/add?venueId=12238&oauth_token="+token);
And this solved the problem. Thanks all

Categories

Resources