Invoking Rest API using java client passing json object - java

I am new to JSON. I am invoking a public rest API
https://api.gdc.cancer.gov/cases
I want to query all the cases for a particular disease type( for example TCGA-LAML mentioned below).
in SOAP Ui when I POST below request in JSON format .It gives me perfect answer
{
"filters":
{"op":"in",
"content":{
"field":"cases.project.project_id",
"value":["TCGA-LAML"]
}
}
}
But I have to call POST through a java client. Even after Trying hard I am not able to set the input parameters correctly.
I am posting my code here. Can you please help me correcting the code.
package downloadtoolproject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Newtest {
public static String sendPostRequest(String requestUrl, String payload) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
{
jsonString.append(line);
System.out.println(line);
}
br.close();
connection.disconnect();
}
catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString() ;
}
public static void main(String [] args)
{
String payload = "{\"field\":\"project_id\",\"value\":[\"TCGA-LAML\"]}";
String requestUrl="https://api.gdc.cancer.gov/cases";
sendPostRequest(requestUrl, payload);
}
}

I think the following solution should work for you
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Newtest {
public static String sendPostRequest(String requestUrl, String payload) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
System.out.println(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
public static void main(String[] args) {
List<String> values = new ArrayList<>();
values.add("TCGA-LAML");
String requestUrl = "https://api.gdc.cancer.gov/cases";
sendPostRequest(requestUrl, preparePayload(values));
}
private static String preparePayload(List<String> values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append("\"" + value + "\",");
}
String desiredValue = sb.toString().substring(0, sb.toString().length() - 1);
return "{ \"filters\": {\"op\":\"in\", \"content\":{ \"field\":\"cases.project.project_id\", \"value\":[" + desiredValue + "] } } }";
}
}
You just need to add all the input values in the values List and pass it to the preparePayload method ,it will convert it into a valid payload.

Related

Minecraft auth server returning 403?

So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.

Send HTTP POST reqeust with Graphql query form java

I want to create a ticket on monday.com. I wrote HTTP method which makes POST call on specific monday server and as a parameter I'm passing graphql query. but unfortunately with no success, I think I'm passing query parameters in a wrong way, but I can't figure what exactly I'm doing wrong.
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Monday {
static int id = 1249501957;
static String token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String query = "mutation {\n"
+ " create_item(item_name:\"heyyyyyyy\", board_id:" + id + "){\n"
+ " id\n"
+ " }\n"
+ "}";
static String targetURL = "https://levank707.monday.com/projects";
public static void main(String[] args) throws Exception {
executePost(targetURL,query);
}
public static String executePost(String targetURL, String query) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/graphql");
connection.setRequestProperty("Content-Length",
Integer.toString(query.getBytes().length));
connection.setRequestProperty("Authorization",token );
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(query);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}}

Download file using REST API

I am trying to call a REST API using Java client.
The Rest API https://api.gdc.cancer.gov/data has files data.
When I append file name to the URL (https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c) I can download the given file from using browser.
here filename is 556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c.
can you please let me know,How can i achieve in this JAVA. The code I am using.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class DownloadFilesAPI {
public DownloadFilesAPI() {
super();
}
public static String sendPostRequest(String requestUrl) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("POST");
// connection.connect();
//Get the response status of the Rest API
// int responsecode = connection.getResponseCode();
//System.out.println("Response code is: " +responsecode);
//connection.getResponseMessage();
// System.out.println(connection.getResponseMessage());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
// System.out.println(connection.getResponseMessage());
// System.out.println( JsonPath.from(requestUrl));
OutputStreamWriter writer = new
OutputStreamWriter(connection.getOutputStream());
writer.write(requestUrl);
writer.close();
/* BufferedReader br = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close(); */
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
public static void main(String[] args) {
List<String> values = new ArrayList<>();
// values.add("556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c");
String requestUrl = "https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c";
sendPostRequest(requestUrl);
}
private static String preparePayload(List<String> values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append("\"" + value + "\",");
}
String Requiredvalue = sb.toString().substring(0, sb.toString().length() - 1);
return "{ \"ids\":[" + Requiredvalue + "] } } }";
}
}
You can't just output a String since you are trying to download a pdf. If you simply want to download the File there is an easier method adapted from this answer:
String requestUrl = "https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c";
URL url = new URL(requestUrl);
InputStream in = url.openStream();
Files.copy(in, Paths.get("your_filename.pdf"), StandardCopyOption.REPLACE_EXISTING);
in.close();
System.out.println("finished!");
I have tested it for the URL you provided and got the pdf File without problems.

Java and REST POST method - how to transform URL POST request to JSON Body POST Request?

I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you

Parsing of the site booking.uz.gov.ua

This code that parses from the site booking.uz.gov.ua. But for some reason, he did not want to work. Who can show why does not work, or fix it?
Who can advise something?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ua.gov.uz.booking.uz.main(uz.java:137)
package ua.gov.uz.booking;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class uz {
static String html = "";
static String cookie = "";
static String token = "";
static String error = "";
static Map<String, List<String>> headers = null;
static void fetchHtml() {
try {
URL url = new URL("http://booking.uz.gov.ua/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
headers = conn.getHeaderFields();
String line;
while ((line = rd.readLine()) != null) {
html += line;
}
rd.close();
} catch (Exception e) {
error = e.getMessage();
}
}
static void parseCookie() {
List<String> cookies = headers.get("Set-Cookie");
for (String current_cookie : cookies) {
if (current_cookie.startsWith("_gv_sessid")) {
cookie = current_cookie;
break;
}
}
}
static void parseToken() {
String adapter = "var token;localStorage={setItem:function(key, value){if(key==='gv-token')token=value}};";
Pattern pattern = Pattern.compile("\\$\\$_=.*~\\[\\];.*\"\"\\)\\(\\)\\)\\(\\);");
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String obfuscated = matcher.group(0);
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
try {
engine.eval(adapter + obfuscated);
} catch (ScriptException e) {
error = e.getMessage();
}
token = engine.get("token").toString();
}
}
static String getStationId(String name) {
String json = "";
try {
URL url = new URL("http://booking.uz.gov.ua/en/purchase/station/" + name + "/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
json += line;
}
rd.close();
} catch (Exception e) {
error = e.getMessage();
}
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.put("json", json);
try {
engine.eval("var station_id = JSON.parse(json).value[0].station_id");
} catch (ScriptException e) {
error = e.getMessage();
}
return engine.get("station_id").toString();
}
static String getData(String fromName, String toName, String date) {
fetchHtml();
parseCookie();
parseToken();
String from = getStationId(fromName);
String to = getStationId(toName);
String json = "";
try {
URL url = new URL("http://booking.uz.gov.ua/en/purchase/search/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.setRequestProperty("GV-Token", token);
conn.setRequestProperty("GV-Ajax", "1");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Referer", "http://booking.uz.gov.ua/en/");
conn.setRequestMethod("POST");
String urlParameters = MessageFormat.format("station_id_from={0}&station_id_till={1}&date_dep={2}" +
"&time_dep=00:00&time_dep_till=24:00", from, to, date);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
json += line;
}
rd.close();
} catch (Exception e) {
error = e.getMessage();
}
return json;
}
static String getData(String fromName, String toName) {
return getData(fromName, toName, new SimpleDateFormat("MM.dd.yyyy").format(new Date()));
}
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Онлайн резервування та придбання квиткiв - Укрзалізниця");
System.out.println("Введите: <start_station> <end_station> [MM.DD.YYYY]");
System.exit(1);
}
String data;
if (args.length > 2)
data = getData(args[0], args[1], args[2]);
else
data = getData(args[0], args[1]);
System.out.println(data);
}
}
Line 137 is args[0] = "dsa". If 0 is an IndexOutOfBound, this means that args is an array with size 0 (i.e. empty). Therefore, you cannot access its index 0, because that requires an array with size >= 1.
How are you launching the program affects the content of the args array (that contains the parameters passed to the program when launched via console). Have you checked what args is when launching with a breakpoint? How do you launch your program? (in the ide, or via console?)
I guess you are running your program directly from main method then initialize args. If you are calling main method from other program then you don't have to initialize args
public static void main(String[] args) {
args = new String[5];
args[0] = "dsa";
.......
}

Categories