Android中的HttpURLConnection网络请求方式

来源:互联网 发布:英雄联盟代练接单软件 编辑:程序博客网 时间:2024/06/08 04:37
String path="http://www.baidu.com";          String param="hehehe";                    //新建一个URL对象          try {              URL url = new URL(path);              // 打开一个HttpURLConnection连接                HttpURLConnection conn = (HttpURLConnection) url.openConnection();              //设置请求方式请求post              conn.setRequestMethod("POST");               // Post请求必须设置允许输出                conn.setDoOutput(true);              // Post请求不能使用缓存                conn.setUseCaches(false);                // 配置请求Content-Type  Content-Length              conn.addRequestProperty("Content-Length", param.length()+"");              conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");              OutputStream out = conn.getOutputStream();              out.write(param.getBytes());              // 开始连接                conn.connect();              int code = conn.getResponseCode();              // 判断请求是否成功                if(code==200){                  InputStream in= conn.getInputStream();                  //把字节流转化成字符流  InputStreamReader                    InputStreamReader isr=new InputStreamReader(in);                  //把字符流转换成缓冲字符流                   BufferedReader br=new BufferedReader(isr);                   // 创建一个StringBuffer                  StringBuffer sb=new StringBuffer();                  String str="";                   while((str=br.readLine())!=null){                       sb.append(str);                   }                                }                        } catch (Exception e) {              // TODO Auto-generated catch block              e.printStackTrace();          }            

 



0 0
原创粉丝点击