Adding body of call to POST using HttpURLConnectio

2020-03-31 06:06发布

I am trying to use HTTPURLConnection make a POST method call to a server api. The JSON version of the body of my call is:

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

How do I add this part using httpURLConnection?

1条回答
地球回转人心会变
2楼-- · 2020-03-31 06:32

i think you can use the Android Rest-Client for sending data to a webservice

take classes RequestMethod.java and RestClient.java from this link https://github.com/TylerSmithNet/RESTclient-Android/tree/master/RESTclient-example/src/com/tylersmith/restclient

and use those in your project like this

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
}
查看更多
登录 后发表回答