如何将curl命令转换为java

如何将curl命令转换为java,java,json,curl,jira-rest-api,Java,Json,Curl,Jira Rest Api,我有下面的curl命令,它给出了一个JSON响应: curl --globoff --insecure --silent -u username:password -X GET -H 'Content-Type: application/json' "http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking" 我想在Java中复制它。谁能告诉我怎么做吗?你可以使用这个代码 String u

我有下面的curl命令,它给出了一个JSON响应:

curl --globoff --insecure --silent -u username:password -X GET -H 'Content-Type: application/json' "http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking"
我想在Java中复制它。谁能告诉我怎么做吗?

你可以使用这个代码

String url = "whatever.your.url.is";
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

connection .setRequestProperty("Content-Type", "application/json");
connection .setRequestMethod("POST");
JSONObject json =new JSONObject();
JSONObject skills =new JSONObject();
skills.put("__op", "AddUnique");
skills.put("objects", new JSONArray(Arrays.asList("flying", "kungfu"));
json.put("skills": skills);
OutputStreamWriter wr= new OutputStreamWriter(connection.getOutputStream());
wr.write(json.toString());
资源链接:

您将需要查看以下内容:

  • (感谢天行者)
基本上,您需要将请求中的“Authorization”头设置为“Basic base64”,其中base64是用户和密码,由冒号分隔,编码为base64

URL url = new URL("http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking")
URLConnection conn = url.openConnection();

String auth = user + ":" + password;
byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
String encodedAuth = Base64.getEncoder().encodeToString(authBytes);
conn.setRequestProperty("Authorization", "Basic " + encodedAuth);

try (InputStream responseStream = conn.getInputStream()) {

    // To read response as a string:
    //MimeType contentType = new MimeType(conn.getContentType());
    //String charset = contentType.getParameter("charset");
    //String response =
    //    new Scanner(responseStream, charset).useDelimiter("\\Z").next();

    // To save response to a file:
    //Path response = Files.createTempFile(null, null);
    //Files.copy(responseStream, response,
    //    StandardCopyOption.REPLACE_EXISTING);

    // To read as JSON object using javax.json library:
    //JsonObject response =
    //    Json.createReader(responseStream).readObject();
}

问题显然是执行Get请求,而不是Post请求。此外,您的代码缺少
connection.setRequestProperty(“授权”、“基本”+encodedString)实际提供授权信息的调用,如您链接到的问题所示。@user3591433都是技能。@SkyWalker我不明白这是如何转换我的卷曲。正如VGR提到的,我的curl正在执行一个get请求。另外,我在哪里进行身份验证?非常感谢。这很有帮助。但是,我无法找到请求的目标错误的有效认证路径。为什么会这样?您正在连接到一个
https:
URL,其服务器正在使用自签名或不匹配的证书,这是无效的,因为它不能安全地保证服务器的身份。有关解决方案和解决方法,请参阅。我在这里遇到错误:String contentType=new MimeType(conn.getContentType());字符串字符集=contentType.getParameter(“字符集”);类型不匹配:无法从MimeType转换为StringYEs,我发现了。请忽略我之前的评论。
String contentType
应该是
MimeType contentType
。我已相应地更新了我的答案。您的其他问题的副本: