我正在尝试使用JAVA HTTPCLIENT发布请求,而这样做的时候,我收到404错误请求。
我尝试在Eclipse中编写Java代码,并收到404错误请求,并尝试通过POSTMAN发送请求,并收到HTTP状态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请求。
答案 0 :(得分:1)
这里的问题归因于一些错误:
因此在这种情况下,为了使其正常工作,请尝试以下操作:
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