android网络编程入门一(HttpURLConnection)

xiaoxiao2021-02-28  30

1.HttpURLConnection的介绍

一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。 

HttpURLConnection给我们提供了两种请求方式:get和post方式

2.get方式请求服务器:

get方式请求服务器:将请求参数放在URL字串后面,如:

new Thread(){ @Override public void run() { //1.准备URL类连接服务器 String path = "http://192.168.56.1:8080/MySERver/LoginServlet"; URL url = null; try {//设置请求头信息 path+= "?password="+ URLEncoder.encode(passwd,"UTF-8")+ "&username="+URLEncoder.encode(username,"UTF-8"); url = new URL(path); //获取HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置请求时间,若超时则返回异常 conn.setConnectTimeout(5000); //设置请求方法 conn.setRequestMethod("GET"); //获取服务器返回的状态码 int code = conn.getResponseCode(); if(code==200){ Log.i("网络:","连接成功了"); //获取服务器输入流 InputStream in=conn.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream();//获取内存输出流                         byte[] buffer = new byte[1024];                         int len = 0;                         while((len = in.read(buffer)) != -1)                         {                             outStream.write(buffer,0,len);                           }                         inStream.close(); //更新UI runOnUiThread(new Runnable() { @Override public void run() { //。。。。。这里写上更新UI的东西 } }); } } catch (Exception e) { e.printStackTrace(); } } }.start();

注意事项:a)由于HttpURLConnection是一个同步请求方法,所以必须放在子线程里面

                 b)get方式的请求参数放在URL字串的后面,并且应该将请求参数放在

           URLEncoder.encode(passwd,"UTF-8")用来解决字符串乱码的问题

3.post方式请求服务器

post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。 

new Thread() { @Override public void run() { //初始化URL URL url = new URL("fa"); HttpURLConnection conn = null; try { 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 is = conn.getInputStream(); // 创建字节输出流对象 ByteArrayOutputStream message = new ByteArrayOutputStream(); // 定义读取的长度 int len = 0; // 定义缓冲区 byte buffer[] = new byte[1024]; // 按照缓冲区的大小,循环读取 while ((len = is.read(buffer)) != -1) { // 根据读取的长度写入到os对象中 message.write(buffer, 0, len); } // 释放资源 is.close(); message.close(); } } catch(Exception e){ e.printStackTrace(); } } };

注意事项:post方式请求也是同步的,所以和get一样需要将需要在子线程中执行,如果需要更新UI的话必须到主线程中更新,这里提供了两种到主线程更新UI的方式一种是Handler,一种是:runOnUiThread;

转载请注明原文地址: https://www.6miu.com/read-2612467.html

最新回复(0)