Question

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

Was it helpful?

Solution

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

OTHER TIPS

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top