HttpURLConnection 使用 Post 方式传递 Json 数据网络请求实例小记

  • Post author:
  • Post category:其他


1、我新建了一个新项目,先添加权限:

<uses-permission android:name="android.permission.INTERNET"/>

2、添加属性(如果网址是 http 的话需要添加,https 不需要添加):

android:usesCleartextTraffic="true"

3、新起一个子线程(网络请求可能比较耗时,不允许在主线程中执行):

    private void startHttpRequestThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                doHttpRequest();
            }
        }).start();
    }

4、定义需要传递给服务器的 json 数据

    private String getJsonContent() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "user123");
        jsonObject.put("password", "psw123");
        jsonObject.put("device", "device123");
        return jsonObject.toString();
    }

5、执行网络请求:

    private void doHttpRequest() {
        try {
            URL url = new URL("http://192.168.xxx.xxx:8080/xxx/login");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection","keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            String json = getJsonContent();
            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
            int responseCode = conn.getResponseCode();
            android.util.Log.e("tag", "responseCode = " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream input = conn.getInputStream();
                StringBuilder sb = new StringBuilder();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb.append((char) ss);
                }
                android.util.Log.e("tag", "请求结果 = " + sb.toString());
                input.close();
            }
            conn.disconnect();
        } catch (Exception e) {
            android.util.Log.e("tag", "出现异常: " + e.toString());
            e.printStackTrace();
        }
    }



版权声明:本文为victor_E_N_01185原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。