Android HttpURLConnection POST/GET

 //新建线程
        new Thread(new Runnable() {
            public void run() {
                try {
                    //将path转成Url格式
                    URL realurl = new URL(path);
                    // 打开和URL之间的连接
                    HttpURLConnection conn = (HttpURLConnection) realurl.openConnection();
                    // http正文内,因此需要设为true, 默认情况下是false;
                    conn.setDoOutput(true);
                    // 设置是否从httpUrlConnection读入,默认情况下是true;
                    conn.setDoInput(true);
                    // 设定请求的方法为"POST",默认是GET
                    conn.setRequestMethod("POST");
                    //设置连接主机超时(单位:毫秒)
                    conn.setConnectTimeout(20000);
                    //设置从主机读取数据超时(单位:毫秒)
                    conn.setReadTimeout(20000);
                    // 获取URLConnection对象对应的输出流
                    PrintWriter oos = new PrintWriter(conn.getOutputStream());
                    // 向对象输出流写出数据,这些数据将存到内存缓冲区中
                    oos.write(sb.toString());
                    // 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)
                    oos.flush();
                    // 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中
                    // 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
                    oos.close();

                     //return response 判断用户是否成功提交
                    int responseCode = conn.getResponseCode();
                    //200请求表示成功,其不成功有500,404等
                    if (responseCode != 200) {
                        Log.e(" Error===" + responseCode,"");
                    } else {
                        Log.d("Post Success!","");
                    }
                    // 调用HttpURLConnection连接对象的getInputStream()函数,
                    // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
                    InputStream in = conn.getInputStream();
                    //将取得的网页返回值进行一次转码,转成自己想要的格式
                    values=changeInputStream(in, code);
                    Log.e("in",values);
                    if(values.equals("true"))
                      returns=true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return returns;
    }

    //转码 Transcoding
    private String changeInputStream(InputStream inputStream, String encode) {
        String result="";
        if(inputStream != null){
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int len = 0;
            try{
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                result = new String(outputStream.toByteArray(), encode);
            }catch (IOException e){
            }
        }
        return result;
    }

 

posted @ 2015-11-05 09:36  Junger  阅读(316)  评论(0编辑  收藏  举报