Android网络操作的几种方法

安卓开发软件:AndroidStudio

服务器软件:Myeclipse+Tomcat

首先无论是哪种方式,安卓手机软件要想联网,必须要申请联网权限(android.permission.INTERNET)

安卓主线程不允许做耗时操作(联网操作就是一种耗时操作),所以下面的的网络操作都是通过内部匿名类另起的一个线程操作的。

一,第一种方式:使用HttpURLConnection进行联网操作

  这个方法需要我们手动构建一个http请求包,发送到指定的服务器

  1. get方式
    1. 设置URL
    2. 打开连接
    3. 设置请求方法为get
    4. 设置连接超时时间
    5. 设置读取超时时间
    6. 把当前的request发送到服务器端
    7. 等待服务器的响应(此处会阻塞)
    8. 获得响应码(并在响应码中做相应的操作),因为安卓子线程内不允许做UI更新的操作,所以需要转到主线程来做(通过安卓中的handler来将信息传递到主线程)
      public void getPic(View v){
              new Thread(new Runnable() {
                  @Override
                  public void run() {
                      try {
                          //首先要支出服务器的地址
                          URL url=new URL("http://192.168.2.1/day10_NetworkServer/brushli.jpg");
                          //通过http连接
                          HttpURLConnection httpurlConnection = (HttpURLConnection) url.openConnection();
                          //设置请求方式,并设置等待响应时间
                          httpurlConnection.setRequestMethod("GET");
                          httpurlConnection.setConnectTimeout(5000);
                          //把当前的request发送到服务器(安卓不允许在主线程内做耗时操作,如连接服务器)
                          httpurlConnection.connect();
                          //发送完连接后等待操作,这个是阻塞式方法,
                          int responseCode = httpurlConnection.getResponseCode();
      
                          //根据得到的响应代码和response的信息作出相应的操作
                          if(responseCode==200){
                              //从服务器读取正确与否的信息
                              InputStream is=httpurlConnection.getInputStream();
                              File file=new File("/data/data/com.rgd.day10_network_3/files");
                              file.mkdir();
                              FileOutputStream fos=new FileOutputStream(new File("/data/data/com.rgd.day10_network_3/files/brushli.jpg"));
                              byte[] buffer=new byte[1024];
                              int read;
                              while ((read =is.read(buffer))!=-1){
                                  fos.write(buffer,0,read);
                              }
                              //由于子线程不允许做UI更新操作,与要通过Handler进行和主线程的通信操作
      
                              Message msg=new Message();
                              msg.what=1;
                              handler.sendMessage(msg);
                              fos.close();
                              is.close();
      
                          }
                      } catch (MalformedURLException e) {
                          e.printStackTrace();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
      
                  }
              }).start();
      
          }
      Handler handler=new Handler(){
              @Override
              public void handleMessage(Message msg) {
                  super.handleMessage(msg);
                  switch(msg.what){
                      case 1:
                          Toast.makeText(MainActivity.this, "保存图片成功", Toast.LENGTH_LONG).show();
                          break;
                      case 2:
                          Toast.makeText(MainActivity.this,"保存MP3成功",Toast.LENGTH_LONG).show();
                          break;
                      case 3:
                          Toast.makeText(MainActivity.this,"保存视频成功",Toast.LENGTH_SHORT).show();
                      default:
                          break;
                  }
              }
          };
      View Code  

    2.post方式  

    • 操作跟get差不多,除了post传递信息是通过正文传递的,而get是放在连接中的
    • new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              //首先要支出服务器的地址
                              URL url=new URL("http://192.168.106.1/day10_NetworkServer/servlet/loginInfo");
                              //通过http连接
                              HttpURLConnection httpurlConnection = (HttpURLConnection) url.openConnection();
                              //设置请求方式,并设置等待响应时间
                              httpurlConnection.setRequestMethod("POST");
                              httpurlConnection.setConnectTimeout(5000);
      
                              String data="username="+username+"&password="+password+"&email="+email+"&phonenumber="+phonenumber;
                              OutputStream outputStream = httpurlConnection.getOutputStream();
                              outputStream.write(data.getBytes());
                              //把当前的request发送到服务器(安卓不允许在主线程内做耗时操作,如连接服务器)
                              httpurlConnection.connect();
                              //发送完连接后等待操作,这个是阻塞式方法,
                              int responseCode = httpurlConnection.getResponseCode();
      
                              //根据得到的响应代码和response的信息作出相应的操作
                              if(responseCode==200){
                                  //从服务器读取正确与否的信息
                                  InputStream is=httpurlConnection.getInputStream();
                                  byte[] buffer=new byte[1024];
                                  int read = is.read(buffer);
                                  String result=new String(buffer,0,read);
                                  //由于子线程不允许做UI更新操作,与要通过Handler进行和主线程的通信操作
                                  Message msg=new Message();
                                  msg.what=1;
                                  handler.sendMessage(msg);
      
                              }else{
                                  Message msg=new Message();
                                  msg.what=-1;
                                  handler.sendMessage(msg);
                              }
                          } catch (MalformedURLException e) {
                              e.printStackTrace();
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
      
                      }
                  }).start();
      View Code

     3.通过  

      

原创作品,转载请注明出处!
原文地址:https://www.cnblogs.com/yidijimao/p/5243900.html