java post 提交数据,Java Post请求与表单数据

本文探讨了在Java中进行POST请求时遇到的问题,即收到了正确的响应状态码200,但响应消息不符合预期。作者指出,可能需要将Content-Type设置为`multipart/form-data`。在Postman中,同样的请求能够得到期望的Token响应。解决方案是显式设置请求头,将`Content-Type`设为`multipart/form-data`,以匹配Postman中的工作示例。
摘要由CSDN通过智能技术生成

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 urlParameters = new ArrayList();

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;

}

}

Following is the Post call sample that is working through Postman app -

pghqy.png

The expected outcome of the post call is supposed to be a Token ie. a String value, current response is -1.

解决方案

Give a try by setting content type multipart/form-data explicitly,

post.setHeader("Content-Type", "multipart/form-data");

In your code ,

post.setEntity(new UrlEncodedFormEntity(urlParameters));

post.setHeader("Content-Type", "multipart/form-data");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值