gpt4 book ai didi

java - 尝试在 HTTPCLIENT -JAVA 中发送 POST 请求时,收到 400 Bad Request

转载 作者:行者123 更新时间:2023-11-30 05:41:19 28 4
gpt4 key购买 nike

我正在尝试使用 JAVA HTTPCLIENT 发布请求,在这样做时,我收到 404 错误请求。

我尝试在 Eclipse 中编写 JAVA 代码并收到 404 Bad Request 并尝试通过 POSTMAN 发送请求并收到 HTTP Status 500

package com.apex.customer.service;

public class CustServicePostTest {

public static void main(String[] args) throws ClientProtocolException, IOException {

String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/102";
//create the http client
HttpClient client = HttpClientBuilder.create().build();
//create the post message
HttpPost post = new HttpPost(url);

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("ID", "102"));
urlParameters.add(new BasicNameValuePair("FIRSTNAME", "Apex"));
urlParameters.add(new BasicNameValuePair("LASTNAME", "Consultancy"));
urlParameters.add(new BasicNameValuePair("STREET", "Shell Blvd"));
urlParameters.add(new BasicNameValuePair("CITY", "Fremont"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);

System.out.println(response.getStatusLine().getStatusCode());
System.out.println("Parameters : " + urlParameters);
System.out.println("Response Code: " + response);
System.out.println(response.getStatusLine().getReasonPhrase());

}

}

我正在寻找 200 OK 请求。

最佳答案

这里的问题是由于一些错误造成的:

  • 首先与输入格式有关。您使用的代码尝试映射键和值,但正如我从 this guide 中看到的那样,它需要纯文本的 XML 格式作为输入。
  • 第二个错误是您试图通过现有 ID 进行发帖。在这种情况下,要创建资源,您应该使用 http://www.thomas-bayer.com/sqlrest/CUSTOMER/

因此,在这种情况下,为了使其正常工作,请尝试如下操作:

        String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);

String xml = "<resource>";
xml += "<ID>102</ID>";
xml += "<FIRSTNAME>Apex</FIRSTNAME>";
xml += "<LASTNAME>Consultancy</LASTNAME>";
xml += "<STREET>Shell Blvd</STREET>";
xml += "<CITY>Fremont</CITY>";
xml += "</resource>";

post.setEntity(new StringEntity(xml));
HttpResponse response = client.execute(post);

System.out.println(response.getStatusLine().getStatusCode());
System.out.println("Response Code: " + response);
System.out.println(response.getStatusLine().getReasonPhrase());

学习使用 curl 命令行实用程序等工具来测试它的另一种方法也非常有用。例如,您可以发布如下产品:

curl -X POST  http://www.thomas-bayer.com/sqlrest/PRODUCT/ -d '<resource><ID>103</ID><NAME>X</NAME><PRICE>2.2</PRICE></resource>'

一旦解决了这个问题,使用HTTP codes就很重要了。 。例如,500 错误意味着服务器端出现问题,而 404 通常意味着您访问了无效端点(它不存在)。

最后,我不会讨论为什么使用这个项目向服务器发送 HTTP 请求 - 但请记住,这不是一种非常常见的方法。目前,使用 JSON 的 REST 会更加有趣和愉快:) 如果您对此感兴趣,请查看 Spring Boot REST

关于java - 尝试在 HTTPCLIENT -JAVA 中发送 POST 请求时,收到 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55583201/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com