簡體   English   中英

在使用 com.google.api.client.http.HttpRequest 的 POST 請求上需要幫助

[英]Need help on POST request using com.google.api.client.http.HttpRequest

我正在嘗試使用com.google.api.client.http.HttpRequest發送發布請求,請求正文中包含數據,但出現錯誤"application/x-www-form-urlencoded" 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);
        }
    }

我認為您的問題不是使用這個特定的 class 發送請求。而是編碼參數本身。 這讓服務器很難解析您的請求,並作為回報給您 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();

您可以使用UrlEncodedContent為您處理 url 編碼,而不是使用ByteArrayContent並自行編碼參數。

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 給你是完全正常的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM