简体   繁体   中英

Server returned HTTP response code: 401 for url when using shopify API

My url as given by the shopify is in this format
https://apikey:password@hostname/admin/orders.json So when trying to get the orders using HttpURLConnection, I am getting 401 unauthorised error. Here is my code

import java.io.*;
import java.net.*;
import java.util.Properties;

/**
 * Created by admin on 22/8/15.
 */
public class Hello {

   // This method should be removed in production
    static void setProxy(){
        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("http.proxyHost","lotus");
        systemProperties.setProperty("http.proxyPort", "8080");
    }
    public static void main(String [] args)
    {
        try
        {

            setProxy();
            URL url = new URL("https://apikey:password@go-frugal.myshopify.com/admin/orders.json");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("user-agent","Mozilla/5.0");
            connection.setRequestProperty("Content-Type","application/json");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while((current = in.readLine()) != null)
            {
                urlString += current;
            }
            System.out.println(urlString);
        }catch(IOException e)
        {
            e.printStackTrace();
        }

    }
}

Here is the error

java.io.IOException: Server returned HTTP response code: 401 for URL: https://apikey:password@go-frugal.myshopify.com/admin/orders.json
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1313)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at Hello.main(Hello.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code 0<br>

getErrorStream returns this

{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}

try this ... your call sequence is wrong. hope this help.

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.jboss.util.Base64;

public class test9 {

public static void main(String[] args) {
    URL url;
    URLConnection urlConn = null;
    HttpURLConnection htcon = null;
    InputStream is = null;
    StringBuffer sb = new StringBuffer();
    String authStr = "apikey:password";

    String authStringEnc = Base64.encodeBytes(authStr.getBytes());

    //String authStringEnc = new String(Base64Encoder.encode(authString.getBytes()));
    try {
        url = new URL("https:go-frugal.myshopify.com/admin/orders.json");
        urlConn = url.openConnection();
        urlConn.setRequestProperty("Authorization", "Basic " +  authStringEnc);
        urlConn.setRequestMethod("GET");
                urlConn.setRequestProperty("user-agent","Mozilla/5.0");
                urlConn.setRequestProperty("Content-Type","application/json");

        htcon = (HttpURLConnection) urlConn;
        is = htcon.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];

        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }   

        System.out.println("sb: "+sb);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

This is an oversight in the way Java handles authorization at the connection level. Took me a good long time to debug; it works in the browser, so why doesn't it work in Java?

Turns out that web browsers will automatically encode the authorization token for any URLs with a user info space. Java doesn't do this by default, so you have to do it yourself:

URI uri = new URL("http://username:password@protected.domain.example/resource").toURI();

String userInfo = uri.getRawUserInfo();
if(userInfo != null && userInfo.length() > 0)
    userInfo = Base64.getEncoder().encodeToString(userInfo.getBytes());

HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
if(userInfo != null && userInfo.length() > 0)
    connection.setRequestProperty("Authorization", "Basic " + userInfo);
connection.connect();

A few notes:

  • You can try using URL#getUserInfo() or URI#getUserInfo() , but there's a small chance that it won't encode passwords with legal special characters correctly.
  • This should work for all HTTP URLs, even if they don't have a user info segment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM