【发布时间】:2018-07-29 18:16:04
【问题描述】:
我是 JSON 新手。我正在调用公共休息 API https://api.gdc.cancer.gov/cases
我想查询特定疾病类型的所有病例(例如下面提到的 TCGA-LAML)。
当我以 JSON 格式发布以下请求时,在 SOAP Ui 中。它给了我完美的答案 { “过滤器”: {“操作”:“在”, “内容”:{ "field":"cases.project.project_id", “价值”:[“TCGA-LAML”] } } }
但我必须通过 java 客户端调用 POST。即使经过努力我也无法正确设置输入参数。
我在这里发布我的代码。你能帮我纠正一下代码吗?
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);
}
}
【问题讨论】:
-
你想运行这个查询吗 :-> { "filters": {"op":"in", "content":{ "field":"cases.project.project_id", "值":["TCGA-LAML"] } } } ?
-
是的 Bhavya 我想运行这个查询。但无法对此进行参数设置。
-
将“String payload”更改为 -> String payload="{ \"filters\": {\"op\":\"in\", \"content\":{ \"field \":\"cases.project.project_id\", \"value\":[\"TCGA-LAML\"] } } }";现在运行你的程序,然后告诉我你是否得到了你想要的输出,如果是,那么我会帮你参数化它!
-
是的,Bhavya 这次给出了预期的结果。
-
很好,现在你要参数化哪个参数?