Sending POST request using com.google.api.client.http.HttpRequest object in Google API
Asked Answered
S

1

17

I have to send POST request with following structure.

    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
    }

I am using below code to send the POST Request but i am getting a response as "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();

I wonder if anyone there who have worked on this similar task can help me out sending the POST request according to the POST request format as mentioned at start of this question.

Stative answered 7/2, 2013 at 12:27 Comment(0)
S
16

I have sent POST request using the below code

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");
Stative answered 8/2, 2013 at 7:38 Comment(2)
Actually I had to replace the first argument of ByteArrayContent.fromString with null, in order to get a correct HTTP request. requestFactory.buildPostRequest(url, ByteArrayContent.fromString(null, requestBody));Hickox
For application/x-www-form-urlencoded use com.google.api.client.http.UrlEncodedContentMaureenmaureene

© 2022 - 2024 — McMap. All rights reserved.