Https:授权401

时间:2019-04-08 11:31:12

标签: java json rest api

我正在尝试建立与API的连接,该API由标头和令牌保护。我已经设置了一个代码,我自己看不到任何错误,现在我碰壁了。我不想做的是从URL中获取一些JSON数据,但是我收到了以下消息:

“服务器返回URL的HTTP响应代码:401:...”

我显示的代码已经过从不安全的API提取JSON的测试,并且可以正常工作。

public static void main(String[] args) {

        String jsonText = "";

        try {                

                String token = "ttn-account-v2.---";

                URL url = new URL("https://---");

                HttpsURLConnection http = (HttpsURLConnection) url.openConnection();

                http.setRequestProperty("Authorization", "Bearer " + token);
                http.setRequestMethod("GET");
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                //http.setRequestProperty("Accept", "application/json");

                System.out.println("token: " + token);

                http.setUseCaches( true );
                http.setDoInput( true );
                http.setDoOutput( true );

                http.connect();

                InputStream im = http.getInputStream();
                StringBuilder sb = new StringBuilder();
                BufferedReader br = new BufferedReader(new InputStreamReader(im));
                FileOutputStream fo = new FileOutputStream("test.txt");
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fo));

                //Object obj = new JSONParser().parse(im);
                String line = br.readLine();

                while (line != null) {
                    sb.append(line + "\n");
                    System.out.println("line: " + line);
                    jsonText = sb.toString();

                    //System.out.println("json: " + jsonText);

                    bw.write(line);
                    bw.newLine();
                    line = br.readLine();

          }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

该代码应打印JSON数据,但我收到http响应401。

堆栈跟踪:

  

java.io.IOException:服务器返回HTTP响应代码:401,URL:https://---       在sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)       在sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)       在sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)

1 个答案:

答案 0 :(得分:2)

可能很远,但是请替换

def start_requests(self):
    url = "https://www.goodreads.com/quotes?page=1",  # <- remove comma here
    yield scrapy.Request(url=url, callback= self.parse)

使用

http.setRequestProperty("Authorization", "bearer" + token);

请注意“载体”和令牌之间的空间。