HTTP post with JSON body using JAVA

huangapple 未分类评论50阅读模式
英文:

HTTP post with JSON body using JAVA

问题

// Java代码部分不要翻译,以下为翻译好的内容:

我正在使用JAVA尝试通过Java发送HTTP post请求到Insight我们的云CMDB)。
由于某种原因我得到了HTTP错误400但我似乎无法找到问题所在也无法找出如何从HTTP调用中检索错误消息

package com.cmdbsync.app;

import java.io.IOException;

import com.google.gson.Gson;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
    
public class App 
{
    public static void main( final String[] args ) throws IOException, InterruptedException
    {
        String pc_data_json = "{\"objectTypeId\": \"90\"," +
            "\"attributes\": [{ " +
                "\"objectTypeAttributeId\": \"365\"," +
                "\"objectAttributeValues\": [{" +
                    "\"value\": \"<PC name>\""+ // PC name
                "}]" +
            "}," +
            "{" +
                "\"objectTypeAttributeId\": \"548\"," +
                "\"objectAttributeValues\": [{" +
                    "\"value\": \"<PC serial>\""+ // PC serial
                "}]" +
            "}," +
            "{" +
                "\"objectTypeAttributeId\": \"380\"," +
                "\"objectAttributeValues\": [{" +
                    "\"value\": \"CM-283\""+
                "}]" +
            "}," +
            "{" +
                "\"objectTypeAttributeId\": \"381\"," +
                "\"objectAttributeValues\": [{" +
                    "\"value\": \"CM-284\""+
                "}]" +
            "}," +
            "{" +
                "\"objectTypeAttributeId\": \"383\"," +
                "\"objectAttributeValues\": [{" +
                    "\"value\": \"4\""+
                "}]" +
            "}]" +
        "}";
            
        Gson gson = new Gson();
        StringEntity entity = new StringEntity(gson.toJson(pc_data_json));

        // HTTP调用
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        try {
            HttpPost request = new HttpPost("https://insight-api.riada.io/rest/insight/1.0/object/create");
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Authorization", "Bearer <api key>");
            request.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(request);

            System.out.println("请求");
            Header[] headers = request.getAllHeaders();
            for (Header header : headers) {
                System.out.println("键: " + header.getName() + ", 值: " + header.getValue());
            }

            System.out.println("响应");
            Header[] header = response.getAllHeaders();
            for (Header head : header) {
                System.out.println("键: " + head.getName() + " , 值: " + head.getValue());
            }
            
            assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    

        } catch (Exception e) {
        } finally {
            System.out.println("完成");
        }
    }
}

pc_data_json字符串应该是正确的 - 这个制作方式的原因是因为我必须导入大约700台计算机,因此我将通过循环读取一个 .csv 文件来运行它,因此希望能够更改计算机名称和计算机序列号。

这是调用程序时的输出:

Picked up JAVA_TOOL_OPTIONS: -Djava.vendor="Sun Microsystems Inc."
请求
键: Content-Type, 值: application/json
键: Authorization, 值: Bearer <api key>
响应
键 : Server , 值 : nginx/1.14.0
键 : Date , 值 : Mon, 04 May 2020 08:43:21 GMT
键 : Content-Type , 值 : application/json
键 : Content-Length , 值 : 883
键 : Connection , 值 : keep-alive
键 : X-Content-Type-Options , 值 : nosniff
键 : X-XSS-Protection , 值 : 1; mode=block
键 : Cache-Control , 值 : no-cache, no-store, max-age=0, must-revalidate
键 : Pragma , 值 : no-cache
键 : Expires , 值 : 0
完成
Exception in thread "main" java.lang.AssertionError:
Expected: <200>
     but: was <400>
        at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
        at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
        at com.cmdbsync.app.App.main(App.java:83)

希望这里的一些高手能够帮助我!
英文:

I'm using JAVA to try send a HTTP post via Java to Insight (Our cloud CMDB).
For some reason, I'm getting a HTTP error 400, and I can't seem to find the issue, and I can't find out how to retrieve the error message from the HTTP call.

package com.cmdbsync.app;

import java.io.IOException;

import com.google.gson.Gson;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
    
public class App 
{
    public static void main( final String[] args ) throws IOException, InterruptedException
    {
        String pc_data_json = &quot;{&quot; + 
                &quot;\&quot;objectTypeId\&quot;: \&quot;90\&quot;,&quot; +
                &quot;\&quot;attributes\&quot;: [{ &quot; +
                    &quot;\&quot;objectTypeAttributeId\&quot;: \&quot;365\&quot;,&quot; +
                    &quot;\&quot;objectAttributeValues\&quot;: [{&quot; +
                        &quot;\&quot;value\&quot;: \&quot;&lt;PC name&gt;\&quot;&quot; + // PC name
                    &quot;}]&quot; +
                &quot;},&quot; +
                &quot;{&quot; +
                    &quot;\&quot;objectTypeAttributeId\&quot;: \&quot;548\&quot;,&quot; +
                    &quot;\&quot;objectAttributeValues\&quot;: [{&quot; +
                        &quot;\&quot;value\&quot;: \&quot;&lt;PC serial&gt;\&quot;&quot; + // PC serial
                    &quot;}]&quot; +
                &quot;},&quot; +
                &quot;{&quot; +
                    &quot;\&quot;objectTypeAttributeId\&quot;: \&quot;380\&quot;,&quot; +
                    &quot;\&quot;objectAttributeValues\&quot;: [{&quot; +
                        &quot;\&quot;value\&quot;: \&quot;CM-283\&quot;&quot; +
                    &quot;}]&quot; +
                &quot;},&quot; +
                &quot;{&quot; +
                    &quot;\&quot;objectTypeAttributeId\&quot;: \&quot;381\&quot;,&quot; +
                    &quot;\&quot;objectAttributeValues\&quot;: [{&quot; +
                        &quot;\&quot;value\&quot;: \&quot;CM-284\&quot;&quot; +
                    &quot;}]&quot; +
                &quot;},&quot; +
                &quot;{&quot; +
                    &quot;\&quot;objectTypeAttributeId\&quot;: \&quot;383\&quot;,&quot; +
                    &quot;\&quot;objectAttributeValues\&quot;: [{&quot; +
                        &quot;\&quot;value\&quot;: \&quot;4\&quot;&quot; +
                    &quot;}]&quot; +
                &quot;}]&quot; +
            &quot;}&quot;;
            
        Gson gson = new Gson();
        StringEntity entity = new StringEntity(gson.toJson(pc_data_json));

        // HTTP calls
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        try {
            HttpPost request = new HttpPost(&quot;https://insight-api.riada.io/rest/insight/1.0/object/create&quot;);
            request.setHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);
            request.setHeader(&quot;Authorization&quot;, &quot;Bearer &lt;api key&gt;&quot;);
            request.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(request);

            System.out.println(&quot;Request&quot;);
            Header[] headers = request.getAllHeaders();
            for (Header header : headers) {
                System.out.println(&quot;Key: &quot; + header.getName() + &quot;, value: &quot; + header.getValue());
            }

            System.out.println(&quot;Response&quot;);
            Header[] header = response.getAllHeaders();
            for (Header head : header) {
                System.out.println(&quot;Key : &quot; + head.getName() + &quot; , value : &quot; + head.getValue());
            }
            
            assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    

        } catch (Exception e) {
        } finally {
            System.out.println(&quot;Done&quot;);
        }
    }
}

The pc_data_json string should be correct - the reason for how this is made, is because I've to import ~700 PCs and therefore will run this through a loop reading a .csv file and therefore want to be able to change PC name and PC Serial.

This is my output when calling the program

Picked up JAVA_TOOL_OPTIONS: -Djava.vendor=&quot;Sun Microsystems Inc.&quot;
Request
Key: Content-Type, value: application/json
Key: Authorization, value: Bearer &lt;api key&gt;
Response
Key : Server , value : nginx/1.14.0
Key : Date , value : Mon, 04 May 2020 08:43:21 GMT
Key : Content-Type , value : application/json
Key : Content-Length , value : 883
Key : Connection , value : keep-alive
Key : X-Content-Type-Options , value : nosniff
Key : X-XSS-Protection , value : 1; mode=block
Key : Cache-Control , value : no-cache, no-store, max-age=0, must-revalidate
Key : Pragma , value : no-cache
Key : Expires , value : 0
Done
Exception in thread &quot;main&quot; java.lang.AssertionError:
Expected: &lt;200&gt;
     but: was &lt;400&gt;
        at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
        at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
        at com.cmdbsync.app.App.main(App.java:83)

Hopyfully some wizard in here can help me!

huangapple
  • 本文由 发表于 2020年5月4日 16:38:45
  • 转载请务必保留本文链接:https://java.coder-hub.com/61588178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定