带有表单数据的 Java Post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45687553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:50:43  来源:igfitidea点击:

Java Post request with form data

javapostpostman

提问by Ani

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 -

我想在 Java 中进行一个简单的 POST 调用,
我得到了 200 响应代码,但是,响应消息错误,
我被告知在使用表单数据时有一种不同的方式进行 Post 调用。

以下是我当前用于进行 post 调用的 Java 代码 -

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;
        }
    }

Following is the Post call sample that is working through Postman app -enter image description here

以下是通过 Postman 应用程序运行的 Post 调用示例 -在此处输入图片说明

I am referring the following website -
https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

我指的是以下网站 -
https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/


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


后调用的预期结果应该是一个令牌,即。字符串值,当前响应为 -1。

回答by Bharat DEVre

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

通过multipart/form-data显式设置内容类型来尝试一下,

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

In your code ,

在您的代码中,

post.setEntity(new UrlEncodedFormEntity(urlParameters)); 
post.setHeader("Content-Type", "multipart/form-data");