增加身体呼叫使用为POST的HttpURLConnection身体、POST、HttpURLConnection

2023-09-07 02:09:51 作者:阿姨,我喜欢你女儿

我想使用的HttpURLConnection进行POST方法调用服务器API。 JSON的版本我的电话的主体是:

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"
}

我如何添加使用HttpURLConnection的这一部分?

How do I add this part using httpURLConnection?

推荐答案

我想你可以使用的Andr​​oid休息 - 客户端,以将数据发送到一个web服务

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

上课 RequestMethod.java RestClient.java 从这个链接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
}