[英]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:一些想法:
"post data".getBytes(StandardCharsets.UTF_8)
"post data".getBytes(StandardCharsets.UTF_8)
connection.getErrorStream()
)connection.getErrorStream()
) 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.