我有我试图发送到Parse.com云功能的字符串。 根据REST API文档( https://www.parse.com/docs/rest#general-requests ),它必须在JSON格式,所以把它做成了JSON对象,并将其转换为一个字符串附加到http请求URL的末尾。
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
String urlParameters = jsonParam.toString();
然后,我发送请求的话,在我试图以满足他们的卷曲的代码示例作为Java代码:
con.setDoOutput(true);
DataOutputStream wr = null;
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
尽管如此,我收到的400返回错误代码错误消息“错误的请求”,我相信通过面目全非参数引起的被发送到云功能。 没有在我的代码触发其他错误。 然而,我通过控制台日志,这些日志验证emailId
是一个正常的字符串,并将所得JSON对象,以及它.toString()
相当于出来作为一个JSON对象的字符串正确读取。 另外这个工作了其他功能我有在我创造我的解析数据库中的对象。 那么为什么会在这里工作?
下面是引用和上下文的全功能:
private void sendEmailWithParse(String emailId) throws IOException {
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
System.out.println("Failed to connect to http link");
e.printStackTrace();
}
//add request header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
System.out.println("Failed to set to POST");
e.printStackTrace();
}
con.setRequestProperty("X-Parse-Application-Id", "**************************************");
con.setRequestProperty("X-Parse-REST-API-Key", "************************************************");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
System.out.println("parameter being sent to cloud function: " + jsonParam);
System.out.println("parameter being sent to cloud function as string: " + jsonParam.toString());
String urlParameters = jsonParam.toString();
// Send post request
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
} catch (IOException e1) {
System.out.println("Failed to get output stream");
e1.printStackTrace();
}
try {
wr.writeBytes(urlParameters);
} catch (IOException e) {
System.out.println("Failed to connect to send over Parse object as parameter");
e.printStackTrace();
}
try {
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.close();
} catch (IOException e) {
System.out.println("Failed to connect to close datastream connection");
e.printStackTrace();
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
System.out.println("Failed to connect to get response code");
e.printStackTrace();
}
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Response message: " + con.getResponseMessage());
}