我使用此代码将 JSON 对象发布到 URL groovy:
def http = new HTTPBuilder( 'myURL' )
// perform a POST request, expecting JSON response data
http.request( POST, JSON ) {
uri.path = myPath
uri.query = [ service_key:'1.0', event_type: 'trigger' ]
headers.'Content-Type' = 'application/json'
// response handler for a success response code:
response.success = { resp, json ->
println resp.status
// parse the JSON response object:
json.responseData.results.each {
ret = json.getText()
println 'Response data: -----'
println ret
println '--------------------'
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.status} : ${resp.statusLine.reasonPhrase}"
}
}
Ajax Code that works:(EDITED)
$.ajax({ url:'https://events.pagerduty.com/generic/2010-04-15/create_event.json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
service_key: "1379ca7018e94343bf5fa5add9fa42eb",
incident_key: "srv01/HTTP",
event_type: "trigger",
description: "TEst Test"
}),
dataType:'json'
});
alert('Message Sent');
每次我收到意外错误:400:错误请求时,如果我使用 $.ajax() 执行此操作,也会发生同样的情况。我收到 HTTP:200 OK 响应。这里出了什么问题?
谢谢。
最佳答案
在 ajax 示例中,您将 4 个元素作为 JSON 正文传递,最终结果如下:
{"service_key": "1379ca7018e94343bf5fa5add9fa42eb",
"incident_key": "srv01/HTTP",
"event_type": "trigger",
"description": "TEst Test"}
但在 groovy 示例中,您仅传递两个查询字符串参数(将在 uri 上传递)。
你可能应该更换
uri.query = [ service_key:'1.0', event_type: 'trigger' ]
与:
body = [service_key:'1.0', incident_key: "srv01/HTTP", event_type: 'trigger' description: "TEst Test"]
您还应该在故障响应处理程序中输出响应数据,因为许多服务都会向您描述为什么不满足服务契约(Contract)。
关于grails - 意外错误 400 :Bad Request HttpBuilder POST Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20574571/