Java - 访问安全HTTPS第三方API

时间:2016-05-05 23:20:28

标签: java maven

我正在编辑Java应用程序并尝试访问安全的第三方API。需要传递两个String变量,以及用于安全访问的ID和标记。下面的代码使用的是Maven。我试图调整Java的代码。

public class JavaApiStreaming {
public static void main (String[]args) throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();

    try {

        // Set these variables to whatever personal ones are preferred
        String domain = "https://stream-fxpractice.oanda.com";// trying to access this api
        String access_token = "ACCESS-TOKEN"; //using this token
        String account_id = "1234567";  //using this ID 
        String instruments = "EUR_USD,USD_JPY,EUR_JPY";

//这是我尝试编辑的代码的一部分。据我所知,这是// maven编码             HttpUriRequest httpGet = new HttpGet(domain +“/ v1 / prices?accountId =”+ account_id +“& instruments =”+ instruments);             httpGet.setHeader(new BasicHeader(“Authorization”,“Bearer”+ access_token));

        System.out.println("Executing request: " + httpGet.getRequestLine());

        HttpResponse resp = httpClient.execute(httpGet);
        HttpEntity entity = resp.getEntity();

        if (resp.getStatusLine().getStatusCode() == 200 && entity != null) {
            InputStream stream = entity.getContent();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));

            while ((line = br.readLine()) != null) {

                Object obj = JSONValue.parse(line);
                JSONObject tick = (JSONObject) obj;

                // unwrap if necessary
                if (tick.containsKey("tick")) {
                    tick = (JSONObject) tick.get("tick");
                }

                // ignore heartbeats
                if (tick.containsKey("instrument")) {
                    System.out.println("-------");

                    String instrument = tick.get("instrument").toString();
                    String time = tick.get("time").toString();
                    double bid = Double.parseDouble(tick.get("bid").toString());
                    double ask = Double.parseDouble(tick.get("ask").toString());

                    System.out.println(instrument);
                    System.out.println(time);
                    System.out.println(bid);
                    System.out.println(ask);
                }
            }
        } else {
            // print error message
            String responseString = EntityUtils.toString(entity, "UTF-8");
            System.out.println(responseString);
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您好像在询问如何使用标准库而不是任何依赖项,并将account_id / access令牌编码为基本身份验证头的一部分。我建议使用HttpURLConnection。它作为Java标准库的一部分包含在内。请尝试以下方法:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.encode(account_id+":"+access_token);
connection.setRequestProperty("Authorization", "Basic "+encoded);