代码之家  ›  专栏  ›  技术社区  ›  Jean-Romain Roy

Firestore使用POST请求和HttpsURLConnection将字段添加到文档

  •  1
  • Jean-Romain Roy  · 技术社区  · 7 年前

    即使在玩了谷歌的API浏览器好几个小时后,我还是想不出来。我想使用文档路径提供的HTTPS请求添加单个字段。

    我的补丁函数示例(此函数有效)

    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();
        }
    }
    

    其他示例my 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 回复  |  直到 7 年前
        1
  •  0
  •   Jean-Romain Roy    7 年前

    我需要使用updateMask字段,

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