如何在Android中使用HttpURLConnection发送Json对象

时间:2016-10-10 21:07:58

标签: java android json http

我正在尝试使用和Android应用程序将Json对象发送到我的Web服务器。我找到的每个例子都使用了已被android 6删除的HttpClient。请有人给我一个HttpURLConnection方法的例子。

1 个答案:

答案 0 :(得分:0)

以下是如何使用HttpURLConnection的示例:

JSONObject json = getJSONData();
String targetURL = getTargetURL();

HttpURLConnection con = (HttpURLConnection)new URL(targetURL).openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setChunkedStreamingMode(0);

StringBuilder output = new StringBuilder();
output.append("data=");
output.append(URLEncoder.encode(data.get(json.toString()), "UTF-8"));

BufferedOutputStream stream = new BufferedOutputStream(con.getOutputStream());
stream.write(output.toString().getBytes());
out.flush();

con.connect();

Exception result = null;
int responseCode = con.getResponseCode();
switch(responseCode) {
    case 200: //all ok
        break;
    case 401:
    case 403:
        // authorized
        break;
    default:
        //whatever else...
        String httpResponse = con.getResponseMessage();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        String line;
        try {
            while ((line = br.readLine()) != null) {
                Log.d("error", "    " + line);
            }
        }
        catch(Exception ex) {
            //nothing to do here
        }

        break;
}

con.disconnect();

那就是说,你应该认真考虑使用一个现有的库,这将隐藏你的大部分内容。