Java 11 HttpClient - POST问题

yv5phkfx  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(49)

我正在编写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中的所有作业。

x9ybnkn6

x9ybnkn61#

你的payload是JSON文本,但mime-type表明它将由urlencoded键值对组成。python代码将导致x-www-form-urlencoded主体:

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

字符串
如果您将此值赋给main-method中的json-String(请重命名它),如

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


有效载荷匹配MIME类型。

相关问题