您好如何使用基于json的API在android中正确发出HTTP post请求。
curl -H "Content-type: application/json" -X POST \
-d '{
"service_key": "e93facc04764012d7bfb002500d5d1a6",
"incident_key": "srv01/HTTP",
"event_type": "trigger",
"description": "FAILURE for production/HTTP on machine srv01.acme.com"
}
}' \
"https://events.pagerduty.com/generic/2010-04-15/create_event.json"
我有这段代码,但它给我的状态错误为400 - https://gist.github.com/26af7af09b509c0e8c2a#comments
答案 0 :(得分:0)
您是否已请求访问网络的权限?看到这个问题(可能重复):
Make an HTTP request with android
<uses-permission android:name="android.permission.INTERNET" />
需要在你的清单中。
答案 1 :(得分:0)
我在这里的其他地方得到了一些代码并且它有效......:)
public void requestAction(String service_key, String event_type, String incident_key, String description)
{
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost("https://events.pagerduty.com/generic/2010-04-15/create_event.json");
JSONObject object = new JSONObject();
try
{
object.put("service_key", service_key);
object.put("event_type", event_type);
object.put("incident_key", incident_key);
object.put("description","PI RedPhone: "+description);
}
catch (Exception ex)
{ }
try
{
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e)
{e.printStackTrace();}
}