Eric Miller Eric Miller - 6 months ago 15
Java Question

Java - Accessing Secure HTTPS Third Party API

I am editing a Java application and trying to access a secure third party API. There are two String variables that need to be passed, and ID and a token for the secure access. The code below is using Maven. I am trying to tweak the code for just 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";


// This is the part of the code I am trying to edi. to my knowledge this is //maven coding
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();
}
}


}

Answer

It seems like you're asking how to use the standard library instead of any dependencies and encode the account_id/access token as part of basic auth header. I would suggest using HttpURLConnection. It's included as part of the Java standard library. Try the following:

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