我按照此处的示例(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对象的方式有问题。有人看到了这个错误吗?
答案 0 :(得分:0)
转储类型,但在设置请求正文后移动行final HttpResponse response = client.execute(request);
解决了问题。
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);
// FROM HERE
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);
// TO HERE
final HttpResponse response = client.execute(request);
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());
}
订单有时很重要:)