我按照此处的示例(Incoming webhook with Python)向环聊聊天室发送了一条简单的消息并按预期工作
from httplib2 import Http
from json import dumps
def main():
url = 'https://chat.googleapis.com/v1/spaces/AAAAUfABqBU/messages?key=<WEBHOCK-KEY>'
bot_message = {
'text' : 'Hello from Python script!'}
message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
现在我想用 Java 实现同样简单的事情,并用这段代码尝试过
private void sendPost() throws IOException {
String url = "https://chat.googleapis.com/v1/spaces/AAAAUfABqBU/messages?key=<WEBHOCK-KEY>";
final HttpClient client = new DefaultHttpClient();
final HttpPost request = new HttpPost(url);
final HttpResponse response = client.execute(request);
request.addHeader("Content-Type", "application/json; charset=UTF-8");
final StringEntity params = new StringEntity("{\"text\":\"Hello from Java!\"}", ContentType.APPLICATION_FORM_URLENCODED);
request.setEntity(params);
final BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
但这会导致错误消息说
{
"error": {
"code": 400,
"message": "Message cannot be empty. Discarding empty create message request in spaces/AAAAUfABqBU.",
"status": "INVALID_ARGUMENT"
}
}
我认为我添加 json 对象的方式有问题。有人看到错误吗?