Prestashop and web service(Restful), HttpURLConnection, BufferedReader - android

I want to access the resources of a site created by prestashop via restful web services, which I enter the URL you must enter a key (that is generated by prestashop when we create a restful web service) in the field of username.
so I am trying to read a xml string:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop>
<manufacturers>
<manufacturer id="1" xlink:href="http://127.0.0.1/test/api/manufacturers/1" />
<manufacturer id="2" xlink:href="http://127.0.0.1/test/api/manufacturers/2" />
</manufacturers>
</prestashop>
over HTTP:
I have the following code:
public class MainTest
{
public static String readUrl(HttpURLConnection conn) throws Exception
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally
{
if (reader != null)
reader.close();
}
}
public static void main(String[] args) throws Exception
{
URL url = new URL("http://127.0.0.1/test/api/manufacturers");
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(30000);
conn.setRequestProperty("Accept", "application/XML");
conn.setRequestProperty("Authentication-Key", "ALHKUNM0J6JJAQC21E4TVWHBM6FAKACF");
System.out.println("true2");
String xml="";
xml = readUrl(conn);
System.out.println(xml);
}
}
but it give me this error
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: http://127.0.0.1/test/api/manufacturers
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.test.services.URLReader.main(URLReader.java:28)
i think the problem is in this ligne
reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));
please help me if you have any solution
regards

You request property for authentication is wrong!
First, Prestashop REST API is using basic authentication.
Then you will need to encrypt your credentials based on base64 encryption.
So download commons-codec-1.5.jar from http://commons.apache.org/proper/commons-codec/.
Here is the way I did it.
import org.apache.commons.codec.binary.Base64
//.....
String username = "Your Prestashop webservice key";
String password = "";// leave it empty
String authToBytes = username + ":" + password;
//....
byte authBytes = Base64.encodeBase64(authToBytes.getBytes())// I keep it generic
String authBytesString = new String(authBytes);
//then your code
conn.setRequestProperty("Authorization", "Basic " + authBytesString);
//...
It should work now.
Find a small Prestashop java API at http://www.onasus.com/2012/10/3712/prestashop-web-services-java-api/
I found many many other ways to consume the web services. One of them uses the class java.net.Authenticator which handles the HTTP Basic authentication for you automatically. Find out more at http://examples.javacodegeeks.com/core-java/net/authenticator/access-password-protected-url-with-authenticator/ .

From HTTP Status Codes:
401 Unauthorized
Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.[2] The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.
Try to find out what kind of authentication your service demands. Often it's easier to play around with curl before you write a program with HttpURLConnection.
curl -v \
-G \
-H 'Accept: application/xml' \
-H 'WWW-Authenticate: Basic 938akjsdfh==' \
http://127.0.0.1/test/api/manufacturers
Another thing: you should always check the response code before accessing getInputStream(). If you encounter something like 4xx, getInputStream() will throw an exception. In this case, maybe you can grab some information of the error if you read from getErrorStream().

Related

Youtube Get uploaded video list. FileNotFound Error

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.

How to Use Both HTTPS and HTTP to parse JSON data in Android?

I followed this to Parse Json In Android
I have Successfully Done it with HttpData handler..
Here I am Successfully Posting Data to server and Getting Response..
Now I want to Use this same in the Part of HTTPS..
Can Any one suggest me How to do this Without Major Changes in my code.. Because In my application I am doing this for more activities.. Please Suggest me to Use HTTPs in my code..
I will provide Additional Info... Depending Responses...
Update
In my code I have Changed HttpURLConnection to HttpsURLConnection
Please suggest me How to through this error In my code..
Update 1
I have Changed Certificate on server side.. Now its working On Https..
But Now,
I want to Use HTTP and HTTPS Both in one app Depending on Client Requirement So here now its worked with Https....
But I also need to work with Http
In my Code Can any any one suggest me...I want I should Work with Https and Http Both In one App.
to use both HTTP and HTTPS, you need to have the 2 methods (i think you already have them)
GetHTTPData(String urlString)
GetHTTPSData(String urlString)
now in HTTPDataHandler class (where you have both methods above)
you need to create a 3rd method GetDataFromUrl(), that will check URL and decide which method to use (http or https)
public String GetDataFromUrl(String url){
if(url.toLowerCase().startsWith("https")){
//HTTPS:
return GetHTTPSData(url);
}else{
//HTTP:
return GetHTTPData(url);
}
}
now in the AsyncTask class ProcessJSON
replace this line stream = hh.GetHTTPData(urlString);
with this one stream = hh.GetDataFromUrl(urlString);
if you don't want to add that 3rd method in HTTPDataHandler, just use the if-statement in ProcessJSON at doInBackground() to call either one of the 2 methods (http or https)
You can use HttpsURLConnection, replace HttpURLConnection by HttpsURLConnection .
public String GetHTTPData(String urlString){
try{
URL url = new URL(urlString);
HttpsURLConnection urlConnection =(HttpsURLConnection)url.openConnection();
// Check the connection status
if(urlConnection.getResponseCode() == 200)
{
// if response code = 200 ok
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// Read the BufferedInputStream
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
stream = sb.toString();
// End reading...............
// Disconnect the HttpURLConnection
urlConnection.disconnect();
}
else
{
// Do something
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
}
// Return the data from specified url
return stream;
}
What I understand is in your server side, they used self signed SSL certificate. So you have to install that certificate in your android device also. Settings > Security > install form storage.But for production build you have to buy ssl certificate from CA Authorities.
Hope this will solve your problem.
Remove HttpDataHandler lines in doInBackground use HttpUrlConnection directly in doInBackground or use HttpUrlConnection in JSONparse class to post params to server follow this tutorial to post params Website

want to build lotus notes leave application for android

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.

Creating a playlist with Youtube DATA API on Android

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".

Better method to store user credentials

Ok, so I am trying to develop a mobile website application for the iPhone and Android. Currently my site uses cURL to log the user into the other site. I have a PHP script that creates a cookie based on the username of the user. cURL then places the info into that cookie. The cookie is stored on my site's host.
Basically this mobile site I am creating is suppose to allow users to log into a forum that I developed this for (site owner would not allow me to create a mobile version on their site so needed to do it on mine). Then once they log in they can read posts and reply to them. When it goes to read a thread needs to load the cookie, as well as when they try to make a post.
How can I get the cookie to save to the users phone rather than my server? The reason I ask is, I'd like it so my host doesn't get filled up with dozens of text files with credentials of users (which I don't want to see so I am not phishing).
I want it so the user signs in, cookie gets saved to the phone. They want to read a post the phone pulls up that cookie. They want to post, phone pulls up the cookie.
I looked into PHP setcookie() function, wasn't sure if that is what I needed.
Any help provided will be appreciated.
When you set a cookie on the server side that cookie gets sent to the client (your phone in this case) via something called HTTP Headers. There is a HTTP Header with the name "Set-Cookie" and a Value of the cookie. When the browser makes a request to the server in the future, its expected to give that value back in a HTTP Header called "Cookie"
So, if you want to set a cookie and use that cookie its a matter of getting the cookie from your request, storing it somewhere safe, and giving it back in future requests.
http://en.wikipedia.org/wiki/HTTP_cookie
Here is a simple Authentication method that takes an url, a username and a password and returns the cookie value.
static public String authenticate(String service_url, String username, String password) throws IOException
{
if (username == null || password == null)
throw new IOException();
String charset = "UTF-8";
URL url = new URL(service_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="+charset);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(5000); // 2 second timeout.
String query = String.format("Email=%s&Password=%s",
URLEncoder.encode(username, charset),
URLEncoder.encode(password, charset));
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
connection.getInputStream();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
if (cookies == null)
throw new IOException();
for (String cookie : cookies)
{
if (cookie.startsWith("authcookie"))
return cookie; // this is the only correct path out.
}
throw new IOException();
}
Example HTTPGET, note the http header to add the cookie value back to requests.
public static InputStream getDataFromHTTP(String url, String authenticationCookie, String mimetype) throws ClientProtocolException, IOException
{
DefaultHttpClient client = getHttpClient();
if (client == null)
throw new IOException("Cant getHttpClient()");
if (url == null)
throw new IOException("URL is null");
HttpGet httpget = new HttpGet(url);
httpget.addHeader("Accept", mimetype);
httpget.addHeader("Cookie", authenticationCookie);
httpget.addHeader("Accept-Encoding", "gzip");
HttpResponse response = client.execute(httpget);
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
return instream;
}

Categories

Resources