使用HttpURLConnection向POST添加调用主体

时间:2012-07-04 09:31:16

标签: android http-post httpurlconnection

我正在尝试使用HTTPURLConnection对服务器api进行POST方法调用。我呼叫主体的JSON版本是:

{
    "grant_type"        : "password",
    "username"          : "perry.marange@zmod.co",
    "password"          : "password"
}

如何使用httpURLConnection添加此部件?

1 个答案:

答案 0 :(得分:1)

我认为您可以使用Android Rest-Client将数据发送到网络服务

从此链接https://github.com/TylerSmithNet/RESTclient-Android/tree/master/RESTclient-example/src/com/tylersmith/restclient

中获取课程RequestMethod.javaRestClient.java

并在您的项目中使用这些

String webServiceUrl = "your-service-url";
RestClient client = new RestClient(webServiceUrl);
String serverResponse = "";
String inputJsonString = "{" + 
    "    \"grant_type\"        : \"password\"," + 
    "    \"username\"          : \"perry.marange@zmod.co\"," + 
    "    \"password\"          : \"password\"" + 
    "}";
client.setJSONString(inputJsonString);
client.addHeader("Content-Type", "appication/json"); // if required
try {
    client.execute(RequestMethod.POST);
    if (client.getResponseCode() != 200) {
        // response error
    }
    else
    {
                    // the response from server
        serverResponse = client.getResponse();
    }
} catch (Exception e) {
    // handle error
}