Firestore使用POST请求和HttpsURLConnection

时间:2018-03-27 06:42:56

标签: android rest httpurlconnection google-cloud-firestore google-apis-explorer

即使在使用谷歌的API资源管理器好几个小时后,我也无法弄明白。我想使用提供文档路径的HTTPS请求添加单个字段。

我的PATCH功能示例(此功能正常)

private void PATCHRequest(String document_path, String theData) throws IOException, JSONException {

    // Build URL
    String FirestoreURL = REST_HEADER + "projects/" + PROJECT_ID + "/databases/(default)/documents/" + document_path;

    // Create URL
    URL cloudFirestoreEndPoint = new URL(FirestoreURL);

    // Create connection
    myHttpsConnection = (HttpsURLConnection) cloudFirestoreEndPoint.openConnection();

    // Set Writable
    myHttpsConnection.setDoOutput(true);

    // Set Request Method
    myHttpsConnection.setRequestMethod("PATCH");

    // Set Https Connection properties
    myHttpsConnection.setRequestProperty("Content-Type", "application/json");

    // Generate JSON from the data
    JSONObject myJSON = getJSONfromString(theData);

    if(myJSON != null){

        // Create output stream linked to our https connection
        OutputStreamWriter streamWriter = new OutputStreamWriter(myHttpsConnection.getOutputStream());

        // Write to buffer
        streamWriter.write(myJSON.toString());

        // Send out the buffer
        streamWriter.flush();

        // Close the stream
        streamWriter.close();
    }
}

其他示例我的DELETE函数,

private void DELETERequest(String document_path) throws IOException {

    // Build URL
    String FirestoreURL = REST_HEADER + "projects/" + PROJECT_ID + "/databases/(default)/documents/" + document_path;

    // Create URL
    URL cloudFirestoreEndPoint = new URL(FirestoreURL);

    // Create connection
    myHttpsConnection = (HttpsURLConnection) cloudFirestoreEndPoint.openConnection();

    // Set Writable
    myHttpsConnection.setDoOutput(true);

    // Set Request Method
    myHttpsConnection.setRequestMethod("DELETE");

    // Send the command
    myHttpsConnection.connect();

    // Result
    myResult_ = "deleted";
}

根据这种格式,是否有人知道如何使用值添加单个字段?

1 个答案:

答案 0 :(得分:0)

我需要使用updateMask字段,

        if(fieldMasks_ != null) {
            for (int i = 0; i < fieldMasks_.size(); ++i) {
                URL_str.append("updateMask.fieldPaths=").append(fieldMasks_.get(i).getName()).append("&");
            }
        }