HttpURLConnection安卓2.3之后之后使用非常好,与2.3之前的Httpclient一样都是进行网络请求的。以下是demo
package com.itheima.rbclient.util; import android.nfc.tech.IsoDep; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * 使用Android的原生2.3以后HttpURLConnection * Created by Administrator on 2016/9/25. * HttpURLConnection网络请求工具类 * 自己玩的 */ public class HttpUtils { public static String get(String path) { String result = ""; //创建统一资源定位符 URL url; try { //1.得到URL路径 url = new URL(path); //通过路径打开链接,因为我们使用的是HttpURLConnection。所以强制转换 // URLConnection urlConnection = url.openConnection(); //2.通过路径打开一个http的链接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //3.设置请求方式 connection.setRequestMethod("Get"); //4.设置连接超时 connection.setConnectTimeout(5000); //5.设置读取超时 connection.setReadTimeout(5000); //6.得到响应码 int code = connection.getResponseCode();//200是成功.404资源没找到.503服务器内部有问题 //7..得到服务器返回的信息类型,写着玩 String contentType = connection.getContentType(); //8.得到当前连接的时间,写着玩 long date = connection.getDate(); if (code == 200) {//表示请求成功 //得到返回的输入流 InputStream is = connection.getInputStream();//服务器给我们的 ByteArrayOutputStream bos = new ByteArrayOutputStream(); //创建缓冲区1k byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } //关闭流和连接 is.close(); bos.close(); //关闭闲置连接 // connection.disconnect(); /*return bos.toString();*/ result = new String(bos.toByteArray(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } return result; } public static String post(String path) { String result = ""; //创建资源定位符 URL url; try { url = new URL(path); //通过路径打开一个Http的连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int code = connection.getResponseCode(); if (code == 200) { InputStream is = connection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer) )!= -1){ bos.write(buffer,0,len); } is.close(); result = bos.toString(); } } catch (Exception e) { e.printStackTrace(); } return result; } }