Android 原生代码实现网络请求

本文导读

  1. 使用URL访问网络资源:下载图片
  2. 使用URLConnection进行网络请求:GET&POST
  3. 使用HttpURLConnection进行网络请求:GET&POST
  4. 原生代码实现及解析:注释
  5. Demo代码下载

使用URL访问网络资源

  • URL对象代表统一资源定位器,指向互联网资源的指针,由协议名,主机,端口和资源组成。
  • URI代表统一资源标识符,不能用于定位资源,唯一的作用就是解析。
  • URL则包含一个可打开该资源书入输入流,因此可以说URL是URI的特例。
URL实现图片下载
private Bitmap bitmap;
Handler handler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
   if (msg.what == 0x123) {
               //使用ImageView显示图片
               ivUrl.setImageBitmap(bitmap);
            }
         }
      };
      new Thread() {
       @Override
       public void run() {
         try {
           URL url = new URL("http://192.168.199.100:8080/image/D.png");//URl对象,指向本地服务器的一张图片
           InputStream is = url.openStream();//打开输入流
           bitmap = BitmapFactory.decodeStream(is);//解析成bitmap对象
           handler.sendEmptyMessage(0x123);//handler机制UI显示图片
           OutputStream os = openFileOutput("demon.png", MODE_PRIVATE);//打开一个文件对应的输入流
           byte[] bytes = new byte[1024];
           int has;
           while ((has = is.read(bytes)) > 0) {
             os.write(bytes, 0, has);//将URL对应的图片下载到本地
          }
          is.close();//关闭流
          os.close();//关闭流
       } catch (Exception e) {
        e.printStackTrace();
     }
  }
}.start();

使用URLConnection进行网络请求

URL的openConnection返回一个URLConnection对象,表示与该URL建议通信连接。通过该对象,可以发送请求,读取资源。
创建URL连接,发生请求,读取资源步骤如下:

  1. 使用openConnection创建一个URLConnection对象
  2. 设置URLConnection的参数和普通请求属性
  3. GET请求,使用connect方法建立连接即可;POST请求,则需要获取URLConnection实例的输出流发送请求参数
  4. 访问资源的输入流读取数据

PS:必须先使用输出流发送请求参数,再使用输入流获取数据

实现URLConnection的GET,POST请求工具类
public class GetPostUrl {
    public static GetPostUrl getPost = new GetPostUrl();//单例

    public static GetPostUrl getGetPost() {
        return getPost;
    }

    /**
     * 发送get请求
     *
     * @param url
     * @return
     */
    public static String get(final String url) {
        final StringBuilder sb = new StringBuilder();
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                BufferedReader br = null;
                InputStreamReader isr = null;
                URLConnection conn;
                try {
                    URL geturl = new URL(url);
                    conn = geturl.openConnection();//创建连接
                    conn.connect();//get连接
                    InputStreamReader isr = new InputStreamReader(conn.getInputStream());//输入流
                    br = new BufferedReader(isr);
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);//获取输入流数据
                    }
                    System.out.println(sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {//执行流的关闭
                    if (br != null) {
                        try {
                        if (br != null) {
                            br.close();
                        }
                        if (isr != null) {
                            isr.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } }}
                return sb.toString();
            }
        });
        new Thread(task).start();
        String s = null;
        try {
            s = task.get();//异步获取返回值
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
 /**
     * POST请求
     *
     * @param url url
     * @param map 请求参数的map集合形式
     * @return
     */
    public static String post(final String url, final Map<String, String> map) {
        final StringBuilder sb = new StringBuilder();
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                DataOutputStream out = null;
                BufferedReader br = null;
                URLConnection conn;
                URL posturl = new URL(url);
                try {
                    conn = posturl.openConnection();//创建连接
                    conn.setDoInput(true);//post请求必须设置
                    conn.setDoOutput(true);//post请求必须设置
                    out = new DataOutputStream(conn
                            .getOutputStream());//输出流
                    StringBuilder request = new StringBuilder();
                    for (String key : map.keySet()) {
                        request.append(key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&");
                    }//连接请求参数
                    out.writeBytes(request.toString());//输出流写入请求参数
                    out.flush();
                    out.close();
                    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));//获取输入流
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    System.out.println(sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {//执行流的关闭
                    if (br != null) {
                        br.close();
                    }
                    if (out != null) {
                        out.close();
                    } }
                return sb.toString(); }
        });
        String s = null;
        new Thread(task).start();
        try {
            s = task.get();//异步获取返回值
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
}

使用HttpURLConnection进行网络请求

HttpURLConnection是URLConnection的子类,在URLConnection的基础上进一步改进增加了操作HTTP资源的便捷方法。
创建URL连接,发生请求,读取资源步骤与URLConnection基本一致。

区别

  1. 使用setRequestMethod()方法设置请求方式”GET”或者”POST”
  2. 使用getResponseCode()获取响应码,判断请求是否成功
  3. 可以使用disconnect()断开请求连接
HttpURLConnection实现GET与POST工具类
public class HttpConnectionUtil {
    public static HttpConnectionUtil http = new HttpConnectionUtil();

    public static HttpConnectionUtil getHttp() {
        return http;
    }

    public String getRequset(final String url) {
        final StringBuilder sb = new StringBuilder();
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL requestUrl = new URL(url);
                    connection = (HttpURLConnection) requestUrl.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    if (connection.getResponseCode() == 200) {
                        InputStream in = connection.getInputStream();
                        reader = new BufferedReader(new InputStreamReader(in));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        System.out.println(sb);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                    if (connection != null) {
                        connection.disconnect();//断开连接,释放资源
                    }
                }
                return sb.toString();
            }
        });
        new Thread(task).start();
        String s = null;
        try {
            s = task.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    public String postRequset(final String url, final Map<String, String> map) {
        final StringBuilder sb = new StringBuilder();
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL requestUrl = new URL(url);
                    connection = (HttpURLConnection) requestUrl.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);//链接超时
                    connection.setReadTimeout(8000);//读取超时
                    //发送post请求必须设置
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setUseCaches(false);
                    connection.setInstanceFollowRedirects(true);
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    DataOutputStream out = new DataOutputStream(connection
                            .getOutputStream());
                    StringBuilder request = new StringBuilder();
                    for (String key : map.keySet()) {
                        request.append(key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&");
                    }              
                    out.writeBytes(request.toString());//写入请求参数
                    out.flush();
                    out.close();
                    if (connection.getResponseCode() == 200) {
                        InputStream in = connection.getInputStream();
                        reader = new BufferedReader(new InputStreamReader(in));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        System.out.println(sb);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        reader.close();//关闭流
                    }
                    if (connection != null) {
                        connection.disconnect();//断开连接,释放资源
                    }
                }
                return sb.toString();
            }
        });
        new Thread(task).start();
        String s = null;
        try {
            s = task.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

}

运行测试

具体测试代码请下载查看,直接上效果图。

Demo Module项目下载

CSDN

http://download.csdn.net/detail/demonliuhui/9836919

GitHub

https://github.com/DeMonLiu623/StudyDemo/tree/master/AndroidNet

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio进行原生的GET请求可以通过使用Java的HttpURLConnection类来实现。下面是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com/api/data"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET connection.setRequestMethod("GET"); // 获取响应码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 读取响应数据 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应数据 System.out.println(response.toString()); } else { System.out.println("GET request failed. Response Code: " + responseCode); } // 关闭连接 connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码,我们首先创建了一个URL对象,指定了要发送GET请求URL地址。然后,我们打开连接并设置请求方法为GET。接下来,我们获取响应码,如果响应码为HTTP_OK(即200),则读取响应数据并进行处理。最后,我们关闭连接。 请注意,上述代码是在Java环境下运行的示例,如果要在Android Studio使用,需要将代码放在适当的位置,例如Activity或Fragment,并在合适的时机调用相关方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值