I'm particularly new to API calling in java to request for XML, so I'm using a template. It can be seen below.
However, now that I'm calling an API from another web API, they require me to use python which I'm clueless about, or use a 3rd party HTTP web client. Instead, I want the calling of the API to be within my java application itself. Is it possible to alter the codes below with the following headers?
Sample request URL: http:// http://ift.tt/1BR4C1T
Request headers: AccountKey=xxx, UniqueUserId=xxx, accept=application/atom+xml
NowCast.java *NowCast.java is linked to a SAX parser
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NowCast extends SAXParser {
public static void main(String[] args) {
String datasetName, keyRef;
datasetName = "Nowcast";
keyRef = "781CF461BB6606ADEA6B1B4F3228DE9DB26ABF1B1B755E93";
NowCast od = new NowCast();
try {
od.callWebAPI(datasetName, keyRef);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void callWebAPI(String datasetName, String keyRef) throws Exception {
// Step 1: Construct URL
String url = "http://ift.tt/1BR4Dmc" + datasetName
+ "&keyref=" + keyRef;
// Step 2: Call API Url
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
// Step 3: Check the response status
if (responseCode == 200) {
// Step 3a: If response status == 200
// print the received xml
super.Parserr(con.getInputStream());
System.out.println(readStream(con.getInputStream()));
} else {
// Step 3b: If response status != 200
// print the error received from server
System.out.println("Error in accessing API - "
+ readStream(con.getErrorStream()));
}
}
// Read the responded result
private String readStream(InputStream inputStream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
return response.toString();
}
}
Aucun commentaire:
Enregistrer un commentaire