Android使用HttpURLConnection Post发送Json数据

        // 创建请求参数的封装的对象
            RequestParams params = new RequestParams();
            //        params.setUseJsonStreamer(true);
            JSONObject body = new JSONObject();
            body.put("username", "panghao");
            body.put("password", "12345");
            String urlPath = "http://192.168.137.1:8080/login";
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 设置允许输出
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            // 设置contentType
            conn.setRequestProperty("Content-Type", "application/json");
            DataOutputStream os = new DataOutputStream( conn.getOutputStream());
            String content = String.valueOf(body);
            os.writeBytes(content);
            os.flush();
            os.close();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
                BufferedReader bf = new BufferedReader(in);
                String recieveData = null;
                String result = "";
                while ((recieveData = bf.readLine()) != null){
                    result += recieveData + "\n";
                }
                in.close();
                conn.disconnect();
            }
        } catch (JSONException e) {
            throw e;
        } catch (IOException io){
            throw io;
        }

你可能感兴趣的:(java)