8

我必須使用以下結構發送POST請求。使用Google API中的com.google.api.client.http.HttpRequest對象發送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錯誤的請求」的響應

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請求。

回答

9

我曾嘗試使用下面的代碼

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"); 
+0

其實我有'null'更換ByteArrayContent.fromString'的'的第一個參數,以獲得正確的HTTP請求發送POST請求。 'requestFactory.buildPostRequest(url,ByteArrayContent.fromString(null,requestBody));' – Davincho

+0

對於'application/x-www-form-urlencoded',使用'com.google.api.client.http.UrlEncodedContent' – Kalem