在android 开发中使用http 协议来与后台交互是一种常见的操作,在android 中主要通过 HttpClient 和 HttpURLConnection 来实现, HttpClient 已经废弃了,在 android 6.0 版本开始移除了对 Apache Http 客户端的支持,如果要继续使用 Apache Http API ,可以在build.gradle 中声明:

android {useLibrary 'org.apache.http.legacy'}

HttpUrlConnection

HttpUrlConnection 继承自 UrlConnection ,抽象类 UrlConnection 是应用程序和Url 之间通信链接的所有类的超类。举个最简单的使用HttpUrlConnection 访问网站的例子:

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   try {     InputStream in = new BufferedInputStream(urlConnection.getInputStream());     readStream(in);   } finally {     urlConnection.disconnect();}

通过新建一个URL 对象,并在URL 类的new 方法中传入要访问的地址,通过url.openConnection() 方法获得一个UrlConnection 对象,在调用 urlConnection.getInputStream() 方法后把请求发送出去并开始接收服务端返回的数据,这个方法返回的输入流不被缓冲,可以使用 BufferedInputStream 封装获得缓冲流。最后再调用 disconnect 断开链接,在古董版本2.2之前有个 bug 需要处理

// Work around pre-Froyo bugs in HTTP connection reuse.if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {  System.setProperty("http.keepAlive", "false");}}

HttpUrlConnection对应的请求方法有GET、POST、OPTION、HEAD、PUT、DELETE、TRACE,可以通过 setRequestMethod 设置,在调用这个方法时如果设置的 method 不能被重置或者对Http 无效会抛ProtocolException,
如果设置了安全管理器并且方法是“TRACE”,但是“allowHttpTrace”NetPermission未被授予则会抛出 SecurityException, 一般常用的接口请求用到 POST 和 GET比较多

使用 post 发送带有参数的http 请求

HttpURLConnection conn;try {    URL url = new URL("http://192.168.98.100:8080/HttpServer/DemoServlet");    conn = (HttpURLConnection) url.openConnection();    //通过setRequestMethod将conn设置成POST方法    conn.setRequestMethod("POST");    //调用conn.setDoOutput()方法以显式开启请求体    conn.setDoOutput(true);    //设置读取超时的时间    conn.setReadTimeout(5000);    //设置链接超时的时间    conn.setConnectTimeout(5000);    //获取请求头    requestHeader = getReqeustHeader(conn);   //获取conn的输出流    PrintWriter pw = new PrintWriter(conn.getOutputStream());   //写入参数    pw.write(param);    pw.flush();   //当调用getInputStream方法时才真正将请求体数据上传至服务器    InputStream is = new BufferedInputStream(conn.getInputStream());    int responseCode = conn.getResponseCode();    if(responseCode != 200) {        Utils.print(" Error===" + responseCode);    } else {        Utils.print("Post Success!");    }} catch (Exception e) {    e.printStackTrace();} finally {    if (conn != null)       conn.close();}

使用 Get 方法发送带有参数的http 请求

发送 Get 请求时其实大部分设置和用 Post 方法差不多,HttpUrlConnection 默认的请求方式也是Get,如果发送的Get 请求带有参数则在请求的URL 地址上拼接上请求的参数。

    HttpURLConnection conn;try {    URL url = new URL("http://192.168.98.100:8080/HttpServer/DemoServlet?page=0");    conn = (HttpURLConnection) url.openConnection();     //获取请求头    requestHeader = getReqeustHeader(conn);   //当调用getInputStream方法时才真正将请求体数据上传至服务器    InputStream is = new BufferedInputStream(conn.getInputStream());    int responseCode = conn.getResponseCode();    if(responseCode != 200) {        Utils.print(" Error===" + responseCode);    } else {        Utils.print("GET Success!");    }} catch (Exception e) {    e.printStackTrace();} finally {    if (conn != null)       conn.close();}

设置 Http 的基本认证

在HTTP中,基本认证(Basic access authentication)是一种用来允许网页浏览器或其他客户端程序在请求时提供用户名和口令形式的身份凭证的一种登录验证方式。在发送之前是以用户名追加一个冒号然后串接上口令,并将得出的结果字符串再用Base64算法编码。例如,提供的用户名是Aladdin、口令是open sesame,则拼接后的结果就是Aladdin:open sesame,然后再将其用Base64编码,得到QWxhZGRpbjpvcGVuIHNlc2FtZQ==。最终将Base64编码的字符串发送出去,由接收者解码得到一个由冒号分隔的用户名和口令的字符串。在使用HttpUrlConnection 请求时,可以通过使用 Authenticator 来进行认证处理。

    Authenticator.setDefault(new Authenticator() {     protected PasswordAuthentication getPasswordAuthentication() {       return new PasswordAuthentication(username, password.toCharArray());     }   });

url请求中添加cookie

引用下维基百科上的cookie 用途的介绍

因为HTTP协议是无状态的,即服务器不知道用户上一次做了什么,这严重阻碍了交互式Web应用程序的实现。在典型的网上购物场景中,用户浏览了几个页面,买了一盒饼干和两瓶饮料。最后结帐时,由于HTTP的无状态性,不通过额外的手段,服务器并不知道用户到底买了什么,所以Cookie就是用来绕开HTTP的无状态性的“额外手段”之一。服务器可以设置或读取Cookies中包含信息,借此维护用户跟服务器会话中的状态。

在 android 中可以使用SDK自带的 CookieHandler 和 CookieManager 来实现

    CookieManager cookieManager = new CookieManager();   CookieHandler.setDefault(cookieManager);

更多相关文章

  1. Android调用JNI出错 java.lang.UnsatisfiedLinkError: No implem
  2. android中使用jni,ndk的C语言回调方法
  3. 通过Android Studio3.5.3编译安装App失败,提示安装包异常解决方
  4. Android 修改app图标和名称的方法
  5. 【Android】adapter has changed解决方法
  6. android中控件点击两次才响应onclick方法
  7. android彻底结束进程的两种方法
  8. android和html交互--动态注入方法

随机推荐

  1. Android 进化
  2. Android Jetpack Navigation 的使用
  3. 怎样使用android自带例子程序
  4. Android AudioRecord录音实现
  5. 【Android】记一次Ninja引发的血案
  6. ReactNative异常:{"errno":-4048,"code":"
  7. 使用Android Studio开发百度地图LBS过程
  8. SQlite与android 的数据交互 (android 项
  9. Android获取本机Mac地址及IP地址的方法
  10. Android程序结构分析