0

我正在尝试使用com.google.api.client.http.HttpRequest请求正文中的数据发送发布请求,但出现错误com.google.api.client.http.HttpResponseException: 400 Bad Request 我需要在"application/x-www-form-urlencoded" 这里发送请求是我的示例:

  public static void sendMessage(String url1, String params){
       
        try {
            String urlParameters  = "{\"name\":\"myname\",\"age\":\"20\"}" ;
            byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
            HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
            GenericUrl url = new GenericUrl(url1);
            HttpContent content = new ByteArrayContent("application/x-www-form-urlencoded", postData);
            HttpRequest request = requestFactory.buildPostRequest(url, content);
            com.google.api.client.http.HttpResponse response = request.execute();
            System.out.println("Sent parameters: " + urlParameters + " - Received response: " + response.getStatusMessage());
            System.out.println("Response content: " + CharStreams.toString(new InputStreamReader(response.getContent())));
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
4

1 回答 1

1

我认为您的问题不是使用这个特定的类发送请求。但是编码参数本身。这使服务器很难解析您的请求,并作为回报给您 400 响应。

您的版本似乎模拟 JSON,但这不是您在 HTTP 中编码参数的方式。正确的方法如下所示:

name=myname&age=20

另外,请记住,您需要对要添加到参数的所有数据进行 url 编码。否则服务器不会理解你的请求,你会再次遇到同样的问题。

在这里:https ://www.baeldung.com/java-url-encoding-decoding#encode-the-url ,你有一些很好的例子来说明如何使用 Java 进行 URL 编码。

编辑:添加示例

以下代码有效:

String urlParameters  = "name=Cezary&age=99" ;
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
HttpTransport transport = new NetHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory();
GenericUrl url = new GenericUrl("http://localhost:8080/greeting");
HttpContent content = new ByteArrayContent("application/x-www-form-urlencoded", postData);
HttpRequest request = requestFactory.buildPostRequest(url, content);
com.google.api.client.http.HttpResponse response = request.execute();

您可以使用它将为您处理 url 编码,而不是自己使用ByteArrayContent和编码参数。UrlEncodedContent

Map<String, Object> params = new HashMap<>();
params.put("name", "Cezary");
params.put("age", 99);
HttpContent content = new UrlEncodedContent(params);

上面提到的代码在接受 HTTP POST 的服务器上进行了测试,该服务器在正文中带有 url 编码参数。如果它仍然不适合你。您应该使用 curl/postman 或其他实用程序来验证您的服务器是否使用该实用程序。如果不是,则完全正常,它会返回 400 给您。

于 2020-07-31T20:36:55.623 回答