我有以下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复制它。谁能告诉我怎么做?
答案 0 :(得分:0)
您可以使用此代码
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());
Java: how to use UrlConnection to post request with authorization?
答案 1 :(得分:0)
你想看看这些:
基本上,您需要设置"授权" “Basic base64 ”请求中的标头,其中 base64 是用户和密码,用冒号分隔,以base 64编码。
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();
}