带表单数据的Java Post请求 [英] Java Post request with form data
问题描述
我想用Java进行简单的POST调用,
我收到200响应码,但是响应消息错误,
有人告诉我,使用表单数据时,可以使用另一种方式进行邮寄呼叫.
以下是我当前用于发帖的Java代码-
I want to make a simple POST call in Java,
I am getting a 200 response code but, with the wrong response message,
I am told there is a different way to make a Post call when using a form data.
Following is my current Java code to make the post call -
private String makePostCall(){
try {
String url = "http://someIp/trusted";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", "app_user"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
以下是通过Postman应用程序运行的Post呼叫示例-
我是指以下网站-
https://www.mkyong.com /java/how-to-send-http-request-getpost-in-java/
邮寄电话的预期结果应该是令牌,即.一个String值,当前响应为-1.
The expected outcome of the post call is supposed to be a Token ie. a String value, current response is -1.
推荐答案
通过显式设置内容类型multipart/form-data
进行尝试,
Give a try by setting content type multipart/form-data
explicitly,
post.setHeader("Content-Type", "multipart/form-data");
在您的代码中,
post.setEntity(new UrlEncodedFormEntity(urlParameters));
post.setHeader("Content-Type", "multipart/form-data");
这篇关于带表单数据的Java Post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!