Android Day21Java之网络

内容

Ⅰ搭建html

Ⅱas代码

具体内容

Ⅰ搭建html

1.html网页搭建

 
 
  
登录
   
 

    

    
 
用户名:


密 码:

2.数据的提交的两种方式
get/GET
向服务器提交数据 并且获取服务器返回的结果
特点:提交的数据都在url里面体现出来
不安全
当提交的数据比较多的时候就无法使用
数据不是特别重要并且少量数据使用get
post/POST
向服务器提交数据 并且获取服务器返回的结果
特点:提交的数据不会在url里面体现出来
安全
可以提交大量数据
3.php的搭建

            

Ⅱas代码

1.使用post上传数据

 //使用post上传简单数据(不是文件)
public static void post() throws IOException {
    //1.创建url
    URL url = new URL("http://127.0.0.1/login.php");

    //2.获取connection对象
    //URLConnection
    //HttpURLConnection 自己需要设定请求的内容
    //请求的方式 上传的内容
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    //3.设置请求方式为post
    connection.setRequestMethod("POST");
    //设置有输出流 需要上传
    connection.setDoOutput(true);
    //设置有输入流 需要下载
    connection.setDoInput(true);
    //4.准备上传的数据
    String data = "user_name = jack&user_pwd = 123";

    //5.开始上传 输出流对象
    OutputStream os = connection.getOutputStream();
    os.write(data.getBytes());
    os.flush();//刷新输出流 写完了

    //6.接收服务器端返回的数据
    InputStream is = connection.getInputStream();
    byte[] buf = new byte[1024];
    int len;
    while ((len = is.read(buf)) != -1) {
        System.out.println(new String(buf, 0, len));
    }
}

2.使用getImage下载数据

public static void getImage() throws IOException {
    //URL
    URL url = new URL("http://127.0.0.1/1.bmp");

    //获取与服务器连接的对象
    URLConnection connection = url.openConnection();

    //读取下载的内容 - 获取输入流
    InputStream is = connection.getInputStream();

    //创建文件保存的位置
    FileOutputStream fos = new FileOutputStream("D:\\Android\\Javahellp\\java\\src\\main\\java\\Day14\\1.jpeg");

    byte[] buf = new byte[1024];
    int len;
    while ((len = is.read(buf)) != -1) {
        fos.write(buf, 0, len);
    }
}

3.带参数的get请求

public static void getParams() throws IOException {
    //使用代码访问(提交/下载)服务器数据
    //URL
    //http://127.0.0.1/login.php?n=jack&p=123
    //1.创建URL
    String path = "http://127.0.0.1/login.php?" + "user_name=jack&user_pwd=123";
    URL url = new URL(path);

    //2.请求方式默认是get
    //获取连接的对象 URLConnection封装了Socekt
    URLConnection connection = url.openConnection();

    //设置请求方式
    HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
    httpURLConnection.setRequestMethod("GET");

    //3.接受服务器端的数据
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    System.out.println(br.readLine());
}

你可能感兴趣的:(Android Day21Java之网络)