0

嗨,我如何使用这个基于 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

4

2 回答 2

0

您是否请求访问网络的权限?请参阅此问题(可能重复):

使用 android 发出 HTTP 请求

<uses-permission android:name="android.permission.INTERNET" />

需要在您的清单中。

于 2012-12-10T16:03:29.267 回答
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();}

}
于 2012-12-13T16:37:36.900 回答