I am trying to use the Youtube GDATA API in order to add a new playlist to a youtube account.
I base my code on the documentation: https://developers.google.com/youtube/2.0/developers_guide_protocol_playlists#Adding_a_playlist
I first get an access token and use my developer key appropriately.
The post seems to work just fine, but when trying to get back the response, I get a file not found exception while calling getInputStream.
Does anyone has an idea?
Thanks
Here is the connection code (an updated cleaner version):
#Override
protected Boolean doInBackground(Void... arg0) {
BufferedReader input = null;
InputStreamReader inputStreamReader = null;
StringBuilder postContentXml = new StringBuilder();
postContentXml.append("<?xml version='1.0' encoding='UTF-8'?>").
append("<entry xmlns='http://www.w3.org/2005/Atom'") .
append(" xmlns:yt='http://gdata.youtube.com/schemas/2007'>").
append("<title type='text'>Sports Highlights Playlist</title>").
append("<summary>A selection of sports highlights</summary>").
append("</entry>");
byte[] buffer = postContentXml.toString().getBytes();
StringBuilder response = new StringBuilder();
try {
URL url = new URL("https://gdata.youtube.com/feeds/api/users/default/playlists");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Initialize connection parameters
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
// Headers initialization
urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
urlConnection.setRequestProperty("Content-Length", String.valueOf(buffer.length));
urlConnection.setRequestProperty("Authorization", mAuthToken);
urlConnection.setRequestProperty("GData-Version", "2");
urlConnection.setRequestProperty("X-GData-Key", YoutubeUtils.getDevKey());
OutputStream os = urlConnection.getOutputStream();
os.write(buffer, 0, buffer.length);
os.flush();
os.close();
InputStream inputStream = urlConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
input = new BufferedReader(inputStreamReader, 4096);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
inputStreamReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("CreatePlaylistTask", "Response: " + response);
}
catch(Exception e) {
Log.d("CreatePlaylistTask", "Error occured: " + e.getMessage());
}
return true;
}
I'm assuming that the POST wasn't actually successful.
If I had to guess from looking at your code, I'd think that the problem might be the Authorization header value. What does myAuthToken look like, and what type of token is it? If it's an OAuth 2 token, for instance, then the value needs to be Bearer TOKEN_VALUE, not just TOKEN_VALUE.
Also, please note that v3 of the YouTube Data API will be released in the near future, and it will offer better support on Android using the new Google APIs Client Library for Java.
I have put together a sample Android application which uses the YouTube Data v3 API to demonstrate how you can load a playlist into a ListView.
https://github.com/akoscz/YouTubePlaylist
Note that you MUST have a valid API key for this sample application to work. You can register your application with the Google Developer Console and enable the YouTube Data API. You need to Register a Web Application NOT an Android application, because the API key that this sample app uses is the "Browser Key".
Related
I am trying to get list of videos uploaded on my YouTube channel using following
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId{MY_CHANNEL_ID}&maxResults=50&key={MY_APP_ID}
I have created App in Google App Console and generate APP ID for the same. But when I trying to access it through my Android application getting java.io.FileNotFoundException error
I have given application identifier and SHA1 also, If I try to access through Web Browser key without any other constrains it works well and returns all the video list but in case of Android it is not working.
#Override
protected String doInBackground(Void... voids) {
HttpURLConnection urlConnection = null;
String urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCrF362wkcVnjqqPRsSEzvgg&maxResults=50&key=AIzaSyAiAFjZb1eVdRxVWnymrhuAb1iDlmYupu8";
//urlString = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLTqSMwQKOhUhl7gm7h6YwX6XPYr0ViBtu&key=AIzaSyAiAFjZb1eVdRxVWnymrhuAb1iDlmYupu8";
String jsonString = new String();
URL url = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonString;
}
Error Log
BasicNetwork.performRequest: Unexpected response code 403 for https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCrF362wkcVnjqqPRsSEzvgg&maxResults=50&key=AIzaSyAiAFjZb1eVdRxVWnymrhuAb1iDlmYupu8
05-13 15:28:26.607 19118-19151/com.jeevanmulmantra W/System.err: java.io.FileNotFoundException: https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCrF362wkcVnjqqPRsSEzvgg&maxResults=50&key=AIzaSyAiAFjZb1eVdRxVWnymrhuAb1iDlmYupu8
Without looking at your API Console settings, I cannot say for sure. But from looking at the HTTP response, it looks like your IP address might be blocked by the Google authorization server. Hence, it is sending you back an unauthorized request HTTP status code 403.
Go to your API Console and select the None radio button from under the Key restrictions section. Then try again. It should work.
This is not exactly what you are asking but I will share my experience.
I had a similar situation a couple of months ago. Seaching on line I got to the conclusion that the YouTube api option for Android just doesn't work. I ended up with a more convenient solution for my development:
I got a YT api key for a website and bound it to the corresponding domain.
I Created a php file that gets the playlist from youtube twice a day using curl and cron job setup on the server. The playlist file in json format is then written to the web server (refreshed twice a day).
The Android app connects to my server intead of YTs and get the "cached" json play list from there.
This option drastically reduces the impact on the quota consumption because all the hits to the playlist go to the website.
If you are interested in this option I can share the php used for getting the play list.
I had the same problem, just regenerate another key and restrict it again with the package name and SHA1 from your Android Studio. It wasn't working with the old key regenerating the key and restricting it again worked for me.
I am reading html source code of a public website using the following code:
Code:
#Override
protected Void doInBackground(Void... params)
{
try
{
URL url = new URL(""+URL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
PageCode = "";
OriginalPageCode = "";
while ((inputLine = in.readLine()) != null)
{
PageCode += inputLine;
}
OriginalPageCode = PageCode;
try
{
extract_website_and_save(); // extracting data from PageCode
}
catch (Exception e1)
{
}
in.close();
}
Background:
The above code sometimes can fetch the most updated website properly. But occasionally it linked to an outdated version of the website and hence unable to obtain the most updated information for the website.
I am curious why the above will occur, does it related to extracting from cache instead of the real updated website??
I therefore used Chrome to browse the same link, and discovered that Chrome also fetched the outdated website.
I have tried restarting the device, but the problem continues.
After 30 minutes to an hour, I requested the app to fetch again and it then can extract the most updated information. I at the same time browse the website using Chrome, Chrome can now obtain the most updated website.
Question:
The above BufferedReader should have no relationship with Chrome? But they follow the same logic and hence extracting from cache instead of from the most updated website?
I strongly suspect the end point is being cached by URL
Try something like this
urlSrt = urlSrt + "?x=" + new Random().nextInt(100000);
// If your URL already is passing parameters i.e. example.com?x=1&p=pass - then modify
// the urlSrt line to to use an "&" and not "?"
// i.e. urlSrt = urlSrt + "&x=" + new Random().nextInt(100000);
URL url = new URL(urlSrt);
URLConnection con = url.openConnection();
con.setUseCaches(false); //This will stop caching!
So if you modify your code to something like this.
URLConnection con = url.openConnection();
con.setUseCaches(false);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
I want to build lotus notes leave application on android. For that purpose I need some lotus script files which will provide me data for showing in my app. But first thing what I need is to get server login
But after trying to login I am not getting proper response. I need advice how can I proceed to build the app leave application for ibm lotus notes.
protected static void tryLogin()
{ ``
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username="+"ABCD"+"password="+"!!!!!!!!";
try
{
url = new URL("http://10.194.5.33/dvlp/wdcidmanage.nsf/hwlsp?wsdl");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
System.out.println("response--------------------------"+response);
// You can perform UI operations here
// Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
System.out.println("error"+"----------------error is there------------");
}
}
this is my code snippet for login. in the server side what i need to do for login ?
If I understood, your need to consume a Domino WS: http://xx.xxx.x.xx/dvlp/wdcidmanage.nsf/hwlsp?wsdl
Ask the Domino administrator to add Anonymous in the ACL of the wdcidmanage.nsf
Consume the WS in androide: http://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/
For an overview of Domino web server authentication see this article. I wrote the article with Domino REST services in mind, but a lot of it applies to SOAP-based services too. This is because authentication is normally done in a layer that's common to REST and SOAP.
You probably want to start with basic authentication. That means sending an Authorization header with each web service request. The value of the Authorization header is just the base64 encoded user name and password as described in this Wikipedia article.
In your comment you said, "when i am trying to establish connection with it it returns me a html page." That sounds like the server is set up for session authentication. As the first article says, you can set up a web site rule to override session authentication for your web service. Then you will get back an HTTP 401 response when the request isn't properly authenticated.
I have a REST service I can't alter, with methods for uploading an image, encoded as a Base64 string.
The problem is that the images can go up to sizes of 5-10MB, perhaps more. When I try to construct a Base64 representation of an image of this size on the device, I get an OutOfMemory exception.
I can however encode chunks of bytes at a time (3000 let's say), but this is useless as I would need the whole string to create a HttpGet/HttpPost object:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.server.com/longString");
HttpResponse response = client.execute(httpGet);
Is there a way of going around this?
Edit: trying to use Heiko Rupp's suggestions + the android doc, I get an exception ("java.io.FileNotFoundException: http://www.google.com") at the following line: InputStream in = urlConnection.getInputStream();
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write("/translate".getBytes());
InputStream in = urlConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
System.out.println("response:" + total);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Am I missing something? The GET request that I need to execute looks like this:
"http://myRESTService.com/myMethod?params=LOOONG-String", so the idea was to connect to http://myRESTService.com/myMethod and then output a few characters of the long string at a time. Is this correct?
You should try to use the URLConnection instead of the apache http client, as this does not require you to hold the object to send in memory, but instead you can do something like:
pseudocode!
HttpUrlConnection con = restUrl.getConnection();
while (!done) {
byte[] part = base64encode(partOfImage);
con.write (part);
partOfImage = nextPartOfImage();
}
con.flush();
con.close();
Also in Android after 2.2 Google recommends the URLConnection over the http client. See the description of DefaultHttpClient.
The other thing you may want to look into is the amount of data to be sent. 10 MB + base64 will take quite a while to transfer (even with gzip compression, which the URLConnection transparently enables if the server side accepts it) over a mobile network.
You must read docs for this REST service, no such service will require you to send such long data in GET. Images are always sent as POST. POST data is always at the end of request and allows to be added iteratively.
I'm developing an android application which is to collect data and then send it to a web directory.
So lets say a want to collect an array of data on the phone, and then after clicking a button send it all to the online directory as a file or stream. It does not even need to get a response - although in the future a confirmation would be handy.
Here is a guess at the sort of order of things...
dir = "someurl.com/data/files_received";
Array data;
sendDataSomehow(dir, data); //obv the difficult bit!
I am in very early stages of developing for Android although I have a lot of experience coding web so that bit will be fine.
I have found suggestions for things such as JSON, Google GSON, HTTP POST and GET - do these sound like the right track?
I hope I have been clear enough.
Yep, JSON would be a good solution for this.
Encode your array as JSON and then send it to your web server as the body of an HTTP POST request. If you have an hour to kill, here's a really good video from Google IO last year explaining how to implement a REST client on Android (what you're doing isn't strictly REST-ful, but the calls you make to the server are very similer): http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html
Right, just wanted to do a quick thank for putting me on the right track. Just had one of those THE CODE WORKS EUREKA moments, very happy. I haven't used JSON but I have managed to pass a variable from Android to SQL through a HTTP-POST and little bit of PHP.
I'm sure this is not the recommended ideology for many reasons although for prototype and presentation it will do just fine!
Here is the code for android:
try {
URL url = new URL("http://www.yourwebsite.com/php_script.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write("stringToPass=I'd like to pass this");
writer.close();
out.close();
if(conn.getResponseCode() != 200)
{
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
conn.disconnect();
} catch (MalformedURLException e1) {
textBox.setText(e1.toString());
} catch (IOException e2) {
textBox.setText(e2.toString());
}
And here is the code for the PHP:
$conn = mysql_connect("localhost","web108-table","********") or die (mysql_error());
mysql_select_db("web108-table",$conn) or die (mysql_error());
$str = $_POST['stringToPass'];
mysql_query("INSERT INTO table(field) VALUES ($str)");
This code works, very simple. Next tests will be to find out if it is suitable for a large number of strings.
I hope this is helpful to somebody else.