android网络连接

1、访问网络的工作不能在主线程(UI)中进行,如果耗时过程则会导致程序出错 ------(子线程中进行)

2、子线程不能更新UI -------(主线程中进行) 即:不能改变界面的显示,比如改变显示的文字,必须转到主线程中set


 new Thread(new Runnable() {
        public void run() {
          
          HttpLogin http=new HttpLogin();
          String str=http.LoginByPost("1", "1");//这是连接的方法
          word = str;
        }
      }).start();


  public  String LoginByPost(String username,String passwd){
      System.out.println("开始线程:");
      String msg = "";  
      try {  
          //初始化URL  
          URL url = new URL(LOGIN_URL);  
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
          //设置请求方式  
          conn.setRequestMethod("POST");  


          //设置超时信息  
          conn.setReadTimeout(5000);  
          conn.setConnectTimeout(5000);  


          //设置允许输入  
          conn.setDoInput(true);  
          //设置允许输出  
          conn.setDoOutput(true);  


          //post方式不能设置缓存,需手动设置为false  
          conn.setUseCaches(false);  


          //我们请求的数据  
          String data = "password="+ URLEncoder.encode(passwd,"UTF-8")+  
                  "&username="+URLEncoder.encode(username,"UTF-8");  


          //獲取輸出流  
          OutputStream out = conn.getOutputStream();  


          out.write(data.getBytes());  
          out.flush();  
          out.close();  
          conn.connect();  


          if (conn.getResponseCode() == 200) {  
              // 获取响应的输入流对象  
              InputStream in = conn.getInputStream();  
              // 创建字节输出流对象  
              ByteArrayOutputStream outMessage = new ByteArrayOutputStream();  
              // 定义读取的长度  
              int len = 0;  
              // 定义缓冲区  
              byte buffer[] = new byte[1024];  
              // 按照缓冲区的大小,循环读取  
              while ((len = in.read(buffer)) != -1) {  
                  // 根据读取的长度写入到os对象中  
                outMessage.write(buffer, 0, len);  
              }  
              // 释放资源  
              in.close();  
              outMessage.close();  
              // 返回字符串  
              msg = new String(outMessage.toByteArray());  


              return msg;  
          }  


      } catch (MalformedURLException e) {  
          e.printStackTrace();  
      } catch (IOException e) {  
          e.printStackTrace();  
      }  
      return msg;  
  }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值