HttpURLConnection请求数据

来源:互联网 发布:gta5捏脸数据女萌妹 编辑:程序博客网 时间:2024/04/27 20:21
private void geData() {
        // 设置接口地址
        try {
            URL url = new URL(path);
            
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            
            // 设置连接超时
            connection.setConnectTimeout(5000);
            // 设置读取超时
            connection.setReadTimeout(5000);
            // 设置请求方式
            connection.setRequestMethod("POST");
            
            //得到输出流,象服务器传递参数
            OutputStream outputStream = connection.getOutputStream();
            
            PrintWriter printWriter=new PrintWriter(outputStream);
            //设置要传递的数据
            printWriter.println(str);
            
            printWriter.flush();
            
            // 连接网络
            connection.connect();
            // 如果响应码等于200代表请求成功
            if (connection.getResponseCode() == 200) {
                // 得到服务器返回的信息,是流的形式返回回来的
                InputStream inputStream = connection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));

                String str;
                StringBuffer stringBuffer = new StringBuffer();
                // 一次读一行
                while ((str = bufferedReader.readLine()) != null) {
                    // 把读到的每一行信息都追加到stringBuffer里
                    stringBuffer.append(str);
                }

                String data = stringBuffer.toString();
                
//                System.out.println(data);
                
                // 将json数据转成对象
                Gson gson = new Gson();

                Bean bean = gson.fromJson(data, Bean.class);
                
                System.out.println(bean.toString());
                // 把对象通过handler发送给主线程
                Message msg = Message.obtain();
//                msg.obj = root;
//                handler.sendMessage(msg);

            } else {

                Toast.makeText(this, "  请求失败 ", 0).show();

            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
0 0
原创粉丝点击