繁体   English   中英

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

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

我正在尝试通过Java将HTTP请求发送到ServiceNow REST API并创建一个事件。

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

身体:

{
    "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.",
}

而且有效,没有问题。

但是在Java中,即时通讯只不过有问题。

我发现我想遵循的最简单的示例在这里: https : //kodejava.org/how-do-i-send-an-http-post-request/

而我的代码:

    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));
        }
    }

但是每当我运行它时,我在java.lang.NoSuchFieldError: INSTANCEHttpClientBuilder.create().build()的第一行遇到一个异常,我也不知道为什么。

有谁知道我在做什么错,或者我可以用其他方式解决这个问题?

根据此质量检查: HttpClientBuilder-java.lang.NoSuchFieldError:INSTANCE,您已经混合使用Apache HTTP客户端的httpcorehttpclient依赖项的不兼容版本。

建议:研究瞬时依赖关系,并尝试通过从依赖关系列表中删除导致该问题的库来解决冲突,或者在项目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>

注意:我为httpclient库选择了最新的兼容版本。 将来可能会更改,或者可能与您当前使用的httpclient版本不匹配。

        CloseableHttpClient httpclient = HttpClients.createDefault();

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

暂无
暂无

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

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