1

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);
    }

}
8
  • Do you want to run this query :-> { "filters": {"op":"in", "content":{ "field":"cases.project.project_id", "value":["TCGA-LAML"] } } } ? Commented Jul 29, 2018 at 19:01
  • Yes Bhavya I want to run this query. But not able to make parameters of this. Commented Jul 29, 2018 at 19:02
  • Change "String payload" to -> String payload="{ \"filters\": {\"op\":\"in\", \"content\":{ \"field\":\"cases.project.project_id\", \"value\":[\"TCGA-LAML\"] } } }"; and now run your program and then tell me if you got your desired output, if yes then I will help you parameterise it! Commented Jul 29, 2018 at 19:04
  • Yes Bhavya this time it is giving desired results. Commented Jul 29, 2018 at 19:08
  • Great, Now which parameter do you want to be parameterised? Commented Jul 29, 2018 at 19:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Its good to hear that. Please accept the answer and close this question. Thanks
Hi Bhavya. Really sorry for again troubling you. { "data": { "hits": [ { "updated_datetime": "2018-05-24T11:22:57.727521-05:00", "submitter_id": "TCGA-AB-2956", "id": "c1f908ce-f6d5-4", "disease_type": "Acute Myeloid Leukemia", } ] portion of response. I want to access submitter_id,id and disease_type in my java code. can you please help with that.
stackoverflow.com/questions/28982412/… this will help you with json parsing
Thanks Bhavya I tried this. But it has some issues json-path 2.4.0 doesn't have the correct API. While in 3.0.0 I get ava.lang.NoClassDefFoundError: io/restassured/internal/assertion/AssertParameter
Use the following pom entry to :-><dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> . and remove the previous one, and I suggest you to start a new thread as answering your queries in comment section is difficult and not properly formatted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.