如何使用HttpUrlConnection进行数据发布?

时间:2016-04-25 21:43:40

标签: android json post httpurlconnection

我有一个你可以在下面看到的ajax代码;

$.ajax({
    url: 'http://www.whoisxmlapi.com/whoisserver/WhoisService',
    dataType: 'jsonp',
    type:'POST',
    data: {
        domainName: 'domaindomanin.com',
        outputFormat: 'json'
    },
    success: function(data) {
    }
});

首先我怎么能在android-java中做到这一点?

是正常的json数据发布和阅读?如果是我怎么能用HttpUrlConnection类做到这一点?我在HttpClient之前使用过,但现在因为我当前的sdk而被淘汰了。

1 个答案:

答案 0 :(得分:0)

这样的事情:

InputStream executePostRequest(HttpURLConnection conn, Request request) 
{
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        String requestString = request.generateBody();
        byte[] outputInBytes = requestString.getBytes("UTF-8");

        OutputStream out = new BufferedOutputStream(conn.getOutputStream());
        out.write(outputInBytes);
        out.flush();
        out.close();

        request.setRequestStatus(conn.getResponseCode());

        try {
            return new BufferedInputStream(conn.getInputStream());
        } catch (IOException err) {
            return new BufferedInputStream(conn.getErrorStream());
        }
    }
}