Java 11 HttpClient - POST 问题

问题描述 投票:0回答:1

我正在编写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:(正在工作。得到 sid 作为输出)

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 作业的列表,而不是像我们在curl 或 python 中看到的 sid)

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代码有什么问题?有没有更好的方法来传递有效负载? 为什么我没有得到 splunk 搜索 id (sid) 作为输出。 我看到一些 20MB 以上的输出,其中列出了 splunk 中的所有作业。

java splunk java-http-client
1个回答
1
投票

您的有效负载是 JSON 文本,但 mime 类型表明它将由 urlencoded 键值对组成。 python 代码生成 x-www-form-urlencoded 主体:

search=%7Ctstats+count+where+index%3Dmain&count=0&output_mode=json

如果您将此值分配给主方法中的

json
字符串(请重命名),例如

String json = "search=%7Ctstats+count+where+index%3Dmain&count=0&output_mode=json";

有效负载与 mime 类型匹配。

© www.soinside.com 2019 - 2024. All rights reserved.