简体   繁体   English

使用基本身份验证和请求正文以Java发送HTTP POST请求

[英]Send HTTP POST request in Java with Basic Auth and request body

I am trying to send an HTTP request through Java to a ServiceNow REST API and create an event. 我正在尝试通过Java将HTTP请求发送到ServiceNow REST API并创建一个事件。

I have this working in Postman with: URL: POST https://<domain>.service-now.com/api/now/table/em_event 我在邮递员中使用以下方法工作:URL: POST https://<domain>.service-now.com/api/now/table/em_event

Body: 身体:

{
    "source":"Postman",
    "node":"Codys Mac",
    "type":"Test",
    "resource":"Test",
    "metric_name":"Testing",
    "event_class":"Test",
    "severity":"4",
    "description":"This is a test event, created from REST API.",
}

and it works, no issues. 而且有效,没有问题。

But in Java, im having nothing but problems. 但是在Java中,即时通讯只不过有问题。

The simplest example I have found that im trying to follow is here: https://kodejava.org/how-do-i-send-an-http-post-request/ 我发现我想遵循的最简单的示例在这里: https : //kodejava.org/how-do-i-send-an-http-post-request/

And my code for this: 而我的代码:

    public void post(){
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(serviceNowURL);

        List<NameValuePair> arguments = new ArrayList<>();
        arguments.add(new BasicNameValuePair("source", "Sample Producer"));
        arguments.add(new BasicNameValuePair("node", "Codys Mac"));
        arguments.add(new BasicNameValuePair("type", "Test Event Type"));
        arguments.add(new BasicNameValuePair("resource", "Test Event Resource"));
        arguments.add(new BasicNameValuePair("metric_name", "Test Event Metric Name"));
        arguments.add(new BasicNameValuePair("event_class", "Test Event Class"));
        arguments.add(new BasicNameValuePair("sevrity", "5"));
        arguments.add(new BasicNameValuePair("description", "This is a test event, created by SampleProducer App usign REST API."));

        try{
            String encoding = Base64.getEncoder().encodeToString((username.concat(":").concat(password)).getBytes("UTF-8"));

            post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            post.setHeader(HttpHeaders.ACCEPT, "application/json");
            post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);
            post.setEntity(new UrlEncodedFormEntity(arguments));
            HttpResponse response = client.execute(post);
        }
        catch(Exception e){
            System.out.println(ExceptionUtils.getRootCauseMessage(e));
        }
    }

But whenever I run this, i encounter an exception on the first line of HttpClientBuilder.create().build() of java.lang.NoSuchFieldError: INSTANCE and i have no idea why. 但是每当我运行它时,我在java.lang.NoSuchFieldError: INSTANCEHttpClientBuilder.create().build()的第一行遇到一个异常,我也不知道为什么。

Does anyone know what im doing wrong, or another way I can approach this? 有谁知道我在做什么错,或者我可以用其他方式解决这个问题?

According to this QA: HttpClientBuilder - java.lang.NoSuchFieldError: INSTANCE you have got a mix of incompartible versions for httpcore and httpclient dependencies of Apache HTTP Client. 根据此质量检查: HttpClientBuilder-java.lang.NoSuchFieldError:INSTANCE,您已经混合使用Apache HTTP客户端的httpcorehttpclient依赖项的不兼容版本。

Advice: investigate the transient dependencies and try to resolve the conflict by removing the libraries that from your dependency list that cause that problem, or explicitly define both libraries in you project pom.xml , eg: 建议:研究瞬时依赖关系,并尝试通过从依赖关系列表中删除导致该问题的库来解决冲突,或者在项目pom.xml明确定义这两个库,例如:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.10</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

Note: I picked the latest compatible versions for httpclient library. 注意:我为httpclient库选择了最新的兼容版本。 This can change in the future or may not match your currently used httpclient version. 将来可能会更改,或者可能与您当前使用的httpclient版本不匹配。

        CloseableHttpClient httpclient = HttpClients.createDefault();

这对我有用,您不必使用连接管理器来打开和关闭连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM