在Java中为https get请求设置标头授权

时间:2017-10-04 05:28:37

标签: java

我正在使用带有头文件授权的休息API的客户端。我正在努力开始添加http标头授权。我正在使用以下代码:

package com.javap;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {


        try {
            sslUtil.turnOffSslChecking();
            Properties prop = new Properties();
            //InputStream input = null;

            InputStream input = Main.class.getResourceAsStream("./application.properties");
            prop.load(input);

            String address = prop.getProperty("address");
            String token = prop.getProperty("token");

            URL url = new URL(address + customerId);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
           conn.setRequestProperty("Authorization",  "Bearer " +  token);

            conn.setRequestMethod("GET");

            conn.setRequestProperty("Accept", "application/json");
            conn.addRequestProperty("User-Agent", "Mozilla/4.0");
            conn.setRequestProperty("Content-Type", "text/plain");
            conn.setRequestProperty("charset", "UTF-8");


            conn.connect();

            if (conn.getResponseCode() != 200) {
                hasSQ = "false";
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }else {
                Scanner sc = new Scanner(url.openStream());
                while(sc.hasNext()){
                    inline += sc.nextLine();
                }
                sc.close();
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

}

我得到401的错误。但是使用Postman,一切正常,儿子,它绝对不是关于令牌。关于如何解决这个问题的任何想法?

提前致谢

1 个答案:

答案 0 :(得分:0)

解决了!显然连接是成功的,但是我通过url.openStream()重新连接到webservice而没有附加的头部授权。这就是原因。我的坏:-p

感谢。