Java使用表单数据进行POST请求

6

我希望在Java中进行简单的POST调用,
我收到了一个200响应代码,但是,响应信息不正确,
据我所知,在使用表单数据时,有一种不同的方法可以进行Post调用。

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

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/
Post调用的预期结果应该是一个令牌,即一个字符串值,而当前的响应为-1。

问题是什么?请提供预期结果与实际结果。 - user7294900
预期的POST调用结果应该是一个Token,即一个字符串值,当前响应为-1。 - Ani
response 的状态码是什么? - Bagus Tesa
如何在Java中将HTTP响应主体作为字符串获取 - user7294900
我收到了一个200响应,但是有人告诉我我传递的表单数据(即app_user)的方式不正确,或者出了什么问题,请查看Postman截图。 - Ani
你能解决这个问题吗? - HemaSundar
2个回答

7

这些回答是正确的,但我努力让它成为可工作的代码。因此,让我提供一个通用且可重复使用的工作答案。

private static RequestConfig requestConfig = RequestConfig.custom().build();

public HttpResponse postWithFormData(String url, List<NameValuePair> params) throws IOException {
        // building http client
        HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        HttpPost request = new HttpPost(url);

        // adding the form data
        request.setEntity(new UrlEncodedFormEntity(params));
        return httpClient.execute(request);
    }

List<NameValuePair> urlParameters = new ArrayList<>();

// add any number of form data
urlParameters.add(new BasicNameValuePair("form_key_1", "form_value_1");
urlParameters.add(new BasicNameValuePair("form_key_2", "form_value_2");

// Getting the HTTP Response and processing it
HttpResponse response = postWithFormData("http_url", urlParameters);
HttpEntity entity = response.getEntity();
// String of the response
String responseString = EntityUtils.toString(entity);
// JSON of the response (use this only if the response is a JSON)
JSONObject responseObject = new JSONObject(responseString);

以下是我主要的导入项,以防任何人对该导入项感到困惑。
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

你的 requestConfig 是什么?在第三行。 - Matt
org.apache.http.client.config.RequestConfig - Shrikant Wandhare
根据我的使用情况稍作修改后,对我很有效。点赞。 - Shrikant Wandhare
具有所有必需导入和依赖项的功能示例,可在replit上填写您的URL/数据。https://replit.com/@domjancik/JavaFormDataPost - domjancik

4

尝试通过明确设置内容类型multipart/form-data来解决问题,

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

在你的代码中,
post.setEntity(new UrlEncodedFormEntity(urlParameters)); 
post.setHeader("Content-Type", "multipart/form-data");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接