16

我必须发送具有以下结构的 POST 请求。

    POST https://www.googleapis.com/fusiontables/v1/tables
    Authorization: /* auth token here */
    Content-Type: application/json

    {
     "name": "Insects",
     "columns": [
     {
        "name": "Species",
        "type": "STRING"
     },
     {
         "name": "Elevation",
         "type": "NUMBER"
     },
    {
         "name": "Year",
         "type": "DATETIME"
    }
      ],
   "description": "Insect Tracking Information.",
   "isExportable": true
    }

我正在使用以下代码发送 POST 请求,但我收到“400 Bad Request”的响应

String PostUrl = "https://www.googleapis.com/fusiontables/v1/tables";
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);

//generate the REST based URL
GenericUrl url = new GenericUrl(PostUrl.replaceAll(" ", "%20"));
//make POST request

String requestBody = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";

HttpRequest request = requestFactory.buildPostRequest(url, ByteArrayContent.fromString(null, requestBody));
request.getHeaders().setContentType("application/json");
// Google servers will fail to process a POST/PUT/PATCH unless the Content-Length
// header >= 1
//request.setAllowEmptyContent(false);
System.out.println("HttpRequest request" + request);
HttpResponse response = request.execute();

我想知道是否有任何从事过类似任务的人可以帮助我根据本问题开头提到的 POST 请求格式发送 POST 请求。

4

1 回答 1

16

我已使用以下代码发送 POST 请求

String requestBody = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";
HttpRequest request = requestFactory.buildPostRequest(url, ByteArrayContent.fromString("application/json", requestBody));
request.getHeaders().setContentType("application/json");
于 2013-02-08T07:38:18.020 回答