我正在编写java HttpClient代码,用于查询splunk API,并获得搜索id(sid)作为输出。我能够用curl和python编写此代码,没有任何问题。但Java被证明是困难的。
Curl:(正在工作。得到SID作为输出)
curl -u user https://url:8089/services/search/jobs -d"search=|tstats count where index=main"
**output:**
<response>
<sid>1352061658.136</sid>
</response>
字符串
Python:(Working. Got sid as output)
import json
import requests
baseurl = 'https://url:8089/services/search/jobs'
username = 'my_username'
password = 'my_password'
payload = {
"search": "|tstats count where index=main",
"count": 0,
"output_mode": "json"
}
headers={"Content-Type": "application/x-www-form-urlencoded"}
response = requests.post(url, auth=(userid,password), data=payload, headers=headers, verify=False)
print(response.status_code)
print(response.text)
型
Java:(不工作。无论请求负载是什么,我们都POST,获得所有SPlunk作业的列表,而不是sid,就像我们在curl或python中看到的那样)
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class HttpClientPostJSON {
private static final HttpClient httpClient = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"user",
"password".toCharArray());
}
})
.build();
public static void main(String[] args) throws IOException, InterruptedException {
// json formatted data
String json = new StringBuilder()
.append("{")
.append("\"search\":\"|tstats count where index=main\"")
.append("}").toString();
// add json header
HttpRequest request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(json))
.header("Content-Type", "application/x-www-form-urlencoded")
.uri(URI.create("https://url:8089/services/search/jobs"))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
}
}
型
java代码有什么问题?有没有更好的方法来传递payload?为什么我没有得到splunk search id(sid)作为输出。我看到一些20MB以上的输出,列出了splunk中的所有作业。
1条答案
按热度按时间x9ybnkn61#
你的payload是JSON文本,但mime-type表明它将由urlencoded键值对组成。python代码将导致x-www-form-urlencoded主体:
字符串
如果您将此值赋给main-method中的
json
-String(请重命名它),如型
有效载荷匹配MIME类型。