简体   繁体   English

Rest API 可以从 Postman 调用,显示来自 ZD52387880E1EA22831817A27 的 400 个错误请求

[英]Rest API can be called from Postman, shows 400 bad request from Java

I am trying to consume a POST restful service.我正在尝试使用 POST 宁静的服务。 When I try it on Postman I get succesful response.当我在 Postman 上尝试时,我得到了成功的响应。 But when I try it on java with below code I am gettin response code 400. In postman I am pasting the same input with replacing escape characters.但是当我用下面的代码在 java 上尝试它时,我得到了响应代码 400。在 postman 中,我粘贴了相同的输入并替换了转义字符。

try {

    URL url = new URL("https://localhost/PasswordVault/api/Accounts");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);

    conn.setRequestProperty("Content-Type", "application/json");
    String input = "{\"qty\":100,\"name\":\"iPad 4\", \"detail\":{\"ver\":\"2020\",\"productionDate\":\"2020\"}}";

    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();


    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();
} catch (Exception e) {
        System.out.println("Exception:- " + e);
}

I would highly recommend that you use a library for this.我强烈建议您为此使用库。 You can use Jackson, this greatly simplifies and standardizes java interaction with remote HTTP services.您可以使用 Jackson,这极大地简化和规范了 java 与远程 HTTP 服务的交互。

Something along these lines will get you started:这些方面的东西会让你开始:

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class ApiClient
{

    private transient Client client;
    protected transient WebTarget apiRoot;

    public ApiClient(String rootUrl) 
    {
        this.client = ClientBuilder.newBuilder().build();
        // The root URL is your API starting point, e.g. https://host/api
        this.apiRoot = client.target(rootUrl);
    }

    public Response doPostToAccounts(String data)
    {
        try 
        {
            // This is where you execute your POST request
            return apiRoot.path("/Accounts")
                .request(MediaType.APPLICATION_JSON)
                .post(Entity.entity(data, MediaType.APPLICATION_JSON));
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

}

Some ideas:一些想法:

  • Encode your request post data in UTF-8: "post data".getBytes(StandardCharsets.UTF_8)在 UTF-8 中编码您的请求发布数据: "post data".getBytes(StandardCharsets.UTF_8)
  • Read the response from the server (not just the code) to hopefully get more details on the problem ( connection.getErrorStream() )阅读来自服务器的响应(不仅仅是代码),以希望获得有关问题的更多详细信息( connection.getErrorStream()
  • Is there a missing authorization header?是否缺少授权 header? (an API token etc.) (API 令牌等)
  • Use single quotes to make your request data string more readable, or use a JSON library to avoid manual mistakes使用单引号使您的请求数据字符串更具可读性,或使用 JSON 库以避免手动错误
  • also call OutputStream.close() after flush()在 flush() 之后也调用 OutputStream.close()

Eg例如

  // handle error code
  if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
    // use getErrorStream for non OK statuses (https://stackoverflow.com/questions/613307/read-error-response-body-in-java)
    String errorMessage = "HTTP response code: " + responseCode
        + (responseMessage == null || responseMessage.trim().length() == 0 ? "" : " " + responseMessage);

    InputStream errorStream = connection.getErrorStream();
    if(errorStream != null) {
      String errorString = streamToString(connection.getErrorStream());
      if(errorString.length() > MAX_MSG_LENGTH) {
        errorString = errorString.substring(0, Math.min(MAX_MSG_LENGTH, errorString.length())) + "...";
      }
      errorMessage += ", HTTP response data: " + errorString;
    }

    throw new RuntimeException(errorMessage);
  }

  // handle OK code
  // ...

First, check the request headers that the postman may be sending and your code does not.首先,检查 postman 可能正在发送而您的代码没有发送的请求标头。 You may need to add some headers to your request before sending it.在发送请求之前,您可能需要在请求中添加一些标头。 Second, I strongly recommend to use some 3d party Http client library instead of coding your HTTP request on your own.其次,我强烈建议使用一些 3d 方 Http 客户端库,而不是自己编写 HTTP 请求。 Some well known libraries are Apache Http client and OK Http client .一些众所周知的库是Apache Http 客户端OK Http 客户端 I personally use my own Http client that is part of a MgntUtils Open source library.我个人使用我自己的 Http 客户端,它是 MgntUtils 开源库的一部分。 You are welcome to try it as well.欢迎您也尝试一下。 Here is simplified code just to demonstrate reading some response from a site:这是简化的代码,仅用于演示从站点读取一些响应:

    try {
        HttpClient client = new HttpClient();
        client.setConnectionUrl("https://www.yahoo.com/");
        String result = client.sendHttpRequest(HttpMethod.GET);
        System.out.println(result);
    } catch (IOException e) {
        System.out.println(TextUtils.getStacktrace(e, "com.mgnt."));
    }
    

But of course you could send POST requests and set Request headers and read textual or binaly response and response headers with this library as well.当然,您也可以使用这个库发送 POST 请求并设置请求标头并读取文本或二进制响应和响应标头。 Here is a link to HttpClient class Javadoc .这是HttpClient class Javadoc的链接。 The library itself is available as Maven artifact and on Github , including Javadoc and source code该库本身可用作Maven 工件Github ,包括 Javadoc 和源代码

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

相关问题 Parse.com REST API错误代码400:从Java HTTP请求到云功能的错误请求 - Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function 从Java应用程序到TFS REST API的HTTP PATCH请求收到400(错误请求)错误 - HTTP PATCH request to TFS REST API from java application getting 400 (bad request) error 从 Rest API 获得 400 错误请求,用于 Keycloak,需要同意 - Getting 400 Bad Request from Rest API for Keycloak with Consent Required ON XMLHttpRequest 从 java 脚本调用时返回错误请求 (400),如果我从 Java 或 Postman 客户端调用它工作正常 - XMLHttpRequest Returning Bad Request (400) while calling from java script , if i am calling from Java or Postman client it working fine Spring Rest 模板 400 错误请求但在 PostMan 上成功 - Spring Rest Template 400 Bad Request but Successful on PostMan Android Rest Api Post 400错误请求 - Android Rest Api Post 400 bad request 呼叫驱动器Rest API:400错误请求 - Call drive Rest API: 400 bad request Java从php上的http请求读取JSON-错误请求400 - Java Reading JSON from http request on php - Bad Request 400 400 来自 Http 请求的错误请求使用 java - 400 Bad request from Http request using java Java APIRest - 使用 GET 方法和 JWT 的 Postman 错误 400 错误请求 - Java APIRest - Postman error 400 bad request with GET method and JWT
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM