• URLConnection(互联网)


    一、urlconnection连接Servlet

    1:> URL请求的类别:
              分为二类,GET与POST请求。二者的区别在于:
                                       a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
                                       b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。

    MyTask.java文件:
    public class MyTask extends AsyncTask {
    
        private BaseAdapter adapter;
        private List<User> userList;
        private MainActivity activity;
        public MyTask(MainActivity activity){
            this.activity = activity;
        }
        private String errorMessage = "";
        private String messageInfo = "";
        private static final String URL_STR = "http://android2017.duapp.com/test1.jsp";
        private String lastId = "123&1=1";
        
        //1.所有耗时的代码,写到这里来(数据库、蓝牙、网络服务)
        //2.绝对不能碰UI
        @Override
        protected Object doInBackground(Object... params) {
            try {
                URL url = new URL(URL_STR);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();//创建了一个连接对象
                //对连接进行配置
                conn.setDoInput(true);//输入
                conn.setDoOutput(true);//输出
                conn.setRequestMethod("POST");
                //防止读取脏数据
                conn.setUseCaches(false);
                
                //获取一个输出流            
                OutputStream os = conn.getOutputStream();
                //可以上传文本数据,通過DataOutputStream写入数据输出流中
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeBytes("lastId="+URLEncoder.encode(lastId, "UTF-8"));
                //dos.writeBytes("lastId="+lastId);
                dos.flush();//刷新,将数据发到缓冲区。
                dos.close();
    // getResponseCode获取URL服务端响应的状态码
    if ( conn.getResponseCode() == 200){ //输入流 InputStream is = conn.getInputStream(); //reader(注意UTF-8读),InputStreamReader 将字节流转换为字符流。是字节流通向字符流的桥梁。
    如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。 
    InputStreamReader isr = new InputStreamReader(is,"UTF-8"); //缓冲区,防止读死 BufferedReader br = new BufferedReader(isr); String ReadOneline = null; //多行数据时,减少不断创建String对象 StringBuffer sb = new StringBuffer(); while ( (ReadOneline=br.readLine())!=null ){ sb.append(ReadOneline); } br.close(); isr.close(); is.close(); conn.disconnect(); return sb.toString(); } else{ errorMessage = "服务器繁忙,请稍后再试("+conn.getResponseCode()+")"; return "errorserver"; } } catch (Exception e) { errorMessage = e.getMessage(); return "errorclient"; } } //准备 @Override protected void onPreExecute() { Toast.makeText(activity, "开始执行...", Toast.LENGTH_SHORT).show(); } //做完后执行 @Override protected void onPostExecute(Object result) { String r = result.toString(); TextView tv = (TextView)activity.findViewById(R.id.textView1); if ("errorclient".equals(r)){ if (errorMessage.indexOf("No add")!=-1){ tv.setText("网络不通"); } else{ tv.setText("访问网络时其它异常:"+errorMessage); } }else if("errorserver".equals(r)){ tv.setText(errorMessage); }else{ tv.setText(r); } } }

    2:> URLConnection的对象: 

    URL url = new URL(URL_STR);
    //URLConnection rulConnection = url.openConnection();//创建了一个连接对象,获取URLConnection对象。 // 此处的urlConnection对象实际上是根据URL的 // 请求协议(此处是http)生成的URLConnection类 // 的子类HttpURLConnection,故此处最好将其转化 // 为HttpURLConnection类型的对象,以便用到
     HttpURLConnection conn = (HttpURLConnection)url
     

    3:> HttpURLConnection对象参数问题

     // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在   
      // http正文内,因此需要设为true, 默认情况下是false;   
      httpUrlConnection.setDoOutput(true);   
       
      // 设置是否从httpUrlConnection读入,默认情况下是true;   
        conn.setDoInput(true);//输入
    conn.setDoOutput(true);//输出
    // Post 请求不能使用缓存,防止读取脏数据 conn.setUseCaches(false); // 设定请求的方法为"POST",默认是GET conn.setRequestMethod("POST"); // 连接,url.openConnection()至此的配置必须要在connect之前完成, // conn.connect(); //实现连接

    4:> HttpURLConnection连接问题:

    //url对象用openconnection()打开连接;获得URLConnection类对象,再用URLConnection类对象的connect()方法进行连接
    //getOutputStream()会隐含的进行connect()方法实现连接。
    OutputStream os =conn.getOutputStream();

    5:> HttpURLConnection写数据与发送数据问题:                      

        //获取一个输出流  

    OutputStream os = conn.getOutputStream();
                //可以上传文本数据,通過DataOutputStream写入数据输出流中
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeBytes("lastId="+URLEncoder.encode(lastId, "UTF-8"));
                //dos.writeBytes("lastId="+lastId);
                dos.flush();//刷新,将数据发到缓冲区。
                dos.close();
    // getResponseCode获取URL服务端响应的状态码 if ( conn.getResponseCode() == 200){
    //输入流,获取服务端返回的

    InputStream is = conn.getInputStream();
                     //reader(注意UTF-8读),InputStreamReader 将字节流转换为字符流。
    是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。 
    InputStreamReader isr = new InputStreamReader(is,"UTF-8"); //缓冲区,防止读死 BufferedReader br = new BufferedReader(isr); String ReadOneline = null; //多行数据时,减少不断创建String对象 StringBuffer sb = new StringBuffer(); while ( (ReadOneline=br.readLine())!=null ){ sb.append(ReadOneline); } br.close();//关闭缓存区 isr.close(); is.close();//关闭输入流
                    conn.disconnect(); return sb.toString();
    } else{
    errorMessage = "服务器繁忙,请稍后再试("+conn.getResponseCode()+")";
    return "errorserver";
    } } catch (Exception e) {
    errorMessage = e.getMessage(); return "errorclient";
    }



  • 相关阅读:
    Git的常用命令收集
    【Android界面实现】使用ScrollingTabsView实现有滑动标签的ViewPager效果
    android ViewPager中页面延迟加载的实现
    android 项目快速修改包名
    Json详细使用(二) 序列话和反序列话
    Json的详细使用(一)处理数组/List/Map
    C++ stack around variable....错误
    刷题-滑动窗口类型 求连续数组最大值
    C# 动态绘制扇形图;
    C# livechart使用
  • 原文地址:https://www.cnblogs.com/wdht/p/6141782.html
Copyright © 2020-2023  润新知