OpenFigi API curl to java POST - java

i am trying to convert the following curl to java and i get the error 400
400 Request body must be an array. The request body is not an array.
curl -v -X POST 'https://api.openfigi.com/v1/mapping'
--header 'Content-Type: text/json'
--data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'
public void r2() throws MalformedURLException, IOException {
//String str = "https://www.openfigi.com/search#!?marketSector=Comdty";
String str = "https://api.openfigi.com/v1/mapping";
URL url = new URL(str);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/json");
String input = "'[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]'";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
/*
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}*/
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
thanks

The program work as expected after removing the ' character in the beginning and ending of input.
String input = "[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();

Related

Response codes from Java.net.Url conection - Rest Webservice Client

I am using Java.Net.URL for making a Rest webservice call.
using the below example code.
URL url = new URL("UrlToConnect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
i am trying to capture response code from this webservice call. I observed that Even after putting a wrong URL i am getting 200 response code from the connection. Please suggest a way by which i can capture response codes 200 , 201 and 202.
Thanks.

Convert curl to httpGet

I am looking to use the following curl request in a java code. I see that we can use httpget to call rest services.
Here is my curl command:
curl -XGET 'localhost:9200/indexname/status/_search' -d '{"_source": {"include": [ "field1", "name1" ]}, "query" : {"term": { "Date" :"2000-12-23T10:12:05" }}}'
How can I put that command in my HttpGet httpGetRequest = new HttpGet(....);
Please advice. Thanks.
You could use the HttpURLConnection.
This code is an example I think it will work for you:
public void get() throws IOException{
//Create a URL object.
String url = "localhost:9200/indexname/status/_search";
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpsURLConnection con = (HttpsURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
String parameters = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}";
//Write the parameter into the Output Stream, flush the data and then close the stream.
wr.writeBytes(parameters);
wr.flush();
wr.close();
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
//Read the POST response.
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save a line of the response.
response.append(inputLine + '\n');
}
br.close();
System.out.println(response.toString());
}
If that doesnt work it's because i must have misstyped the parameters, try it anyway
The combination -X GET and -d results in your data being appended to the URL in application/x-www-form-urlencoded format.
Therefore, I suggest using URLEncoder as follows:
String host = "localhost:9200/indexname/status/_search";
String data = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}";
String url = host + "?" + URLEncoder.encode(data, "UTF-8");

Convert Curl to Java equivalent

I'm working with New Relic REST API for the first time, I have a curl command:
curl -X GET 'https://api.newrelic.com/v2/applications/appid/metrics/data.json' \
-H 'X-Api-Key:myApiKey' -i \
-d 'names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp'
I want to send this command in a java servlet and get a JSON object from the response ready for parsing, What is the best solution?
HttpURLConnection?
Apache httpclient?
I've tried a few different solutions, but nothing has worked so far and most examples I could find are using the depreciated DefaultHttpClient
Here is an example of one of my attempts:
String url = "https://api.newrelic.com/v2/applications.json";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-Api-Key", "myApiKey");
conn.setRequestMethod("GET");
JSONObject names =new JSONObject();
try {
names.put("names[]=", "EndUser/WebTransaction/WebTransaction/JSP/index.jsp");
} catch (JSONException e) {
e.printStackTrace();
}
OutputStreamWriter wr= new OutputStreamWriter(conn.getOutputStream());
wr.write(names.toString());
Edit
I've modified the code a bit, it's working now thanks.
String names = "names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp";
String url = "https://api.newrelic.com/v2/applications/myAppId/metrics/data.json";
String line;
try (PrintWriter writer = response.getWriter()) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("X-Api-Key", "myApiKey");
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(names);
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.println(HTML_START + "<h2> NewRelic JSON Response:</h2><h3>" + line + "</h3>" + HTML_END);
}
wr.close();
reader.close();
}catch(MalformedURLException e){
e.printStackTrace();
}
curl -d sends whatever you specify without formatting it in any way. Just send the string names[]=EndUser/... in the OutputStream, without wrapping it in a JSONObject. Don't forget to call wr.flush() after writing the string. And of course, after that, you need to get the InputStream and start reading from it (I only mention this because it's not in your snippet).

Receiving encoded response to HttpsURLConnection GET request

I am working on an Android app which will connect to a webpage using the java class HttpsURLConnection and parse the HTML response using JSoup. The issue is that the HTML response from the website appears to be encoded. Any ideas on what I can do to get the actual HTML?
Here is my code for contacting the website:
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8,en-GB;q=0.6");
conn.setRequestProperty("Accept-Encoding" , "gzip, deflate, sdch");
conn.setRequestProperty("Connection" , "keep-alive");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
Log.v(TAG,"\nSending 'GET' request to URL : " + url);
Log.v(TAG,"Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
And a snippet of the response:
��������������]�r�6��۞�w#ՙ�NDQ�ﱥ|�siv�Kkw�m&�HH�M, Z��ff_c_o�d�#���9�l�6����� �_=w|����/A{��!W� LZ��������f]�=wc߽�2,˨�|�8x��~�}�x1�$Ib�Uq�7�j�X|;��K
EDIT: The HTML was encoded with GZIP, as shown in the request headers here.
The solution to this issue was to use the GZIPInputStream class as shown below:
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(conn.getInputStream())));
Based on the headers returned with the request, we can conclude that the content is encoded using gzip. Luckily, there is an easy method to decode a gzip encoding stream, using the GZIPInputStream class.
Don't know which URL you are trying to access, but have you tried setting the charset ?
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF8"));

cURL command to Java

I have a cURL command I want to translate in Java
curl -H "Key: XXX" -d url=http://www.google.com http://myapi.com/v2/extraction?format=json
It works fine.
I started to do in Java: (CODE EDITED, it works)
try {
// POST
System.out.println("POSTING");
URL url = new URL("http://myapi.com/v2/extraction?format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Key", "XXX");
String data = "http://www.google.com";
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("url=" +data);
writer.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + data);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("REPOSNE" +response.toString());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
But I don't know how to set my arguments.
Thanks for your help.
Jean
If you mean to set a header field Key with value XXX you can use the setRequestProperty
ie
conn.setRequestProperty("Key", "XXX");
If you want to send data, use
String data = "url=http://www.google.com";
conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
EDIT:-
For posting data as form url encoded, try the following code
String data = "url=" + URLEncoder.encode("http://www.google.com", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
wr.write(data.getBytes());

Categories

Resources