一、URLConnection
1.1、URLConnection参数详解
URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。另外一个重要的类是URL,通常URL可以通过传给构造器一个String
类型的参数来生成一个指向特定地址的URL实例。每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请
求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响。如果在调用
disconnect()时持久连接空闲,则可能关闭基础套接字。
注意:
网络在主线程的异常,不允许在主线程里面进行网络请求。
访问网络权限android.permission.INTERNET。(仅限低版本)。
Android在子线程进行耗时操作,更新UI只能在主线程。
1.2、Post和Get区别
- get没有请求体,post有请求体。
- get请求的参数会跟在请求路径的后面并以 ? 的形式拼接,多个请求参数通过&分隔。
- post有请求体,请求参数在请求体中出现,多个请求参数通过$来分隔。
- get请求的参数还会在请求的url地址中出现,直接可以通过url地址栏就可以看到。
注:get请求由于请求参数在url地址后,所以请求的参数不能过大,不会超过1kb,而post请求没有限制,因为参数都在请求体中
1.3、发送Get请求实例
private void sendGetRequest(String username, String password) { try { // 10.0.2.2是android模拟器访问pc的ip String path = "http://10.0.2.2:8080/ServerProgram/servlet/RequestDemo1?username="+ username +"&password=" + password; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5 * 1000); connection.setReadTimeout(5 * 1000); connection.setRequestMethod("GET");//connection.setRequestProperty(field, newValue); int code = connection.getResponseCode(); if(code == 200){ InputStream in = connection.getInputStream(); // 流 -> 字符串 ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = -1; while((len = in.read(buf)) != -1){ baos.write(buf, 0, len); } String resule = new String(baos.toByteArray(), "utf8"); if(!"".equals(resule)){ System.out.println(resule); } baos.close(); in.close(); } } catch (Exception e) { e.printStackTrace(); } }
其中setRequestProperty()方法是设置头报文属性,例如
<meta http-equiv= "Content-Type"contect="text/html";charset=gb_2312-80">
1.4、发送Post请求实例
private void sendPostRequest(String username, String password) { try { String params = "{\"username\":\"123456\",\"password\":123456}"; byte[] data = params.getBytes("UTF-8"); // 10.0.2.2是android模拟器访问pc的ip String path = "http://10.0.2.2:8080/ServerProgram/servlet/RequestDemo1"; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5 * 1000); connection.setReadTimeout(5 * 1000); connection.setRequestMethod("POST"); // 设置是否将输出放在正文内,post请求必须设置,默认是false,会拼接在url后面 connection.setDoOutput(true); connection.setDoInput(true); // 设置不使用缓存 connection.setUseCaches(false); // 设置头报文属性,也可以用来自定义头发送数据 connection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8"); connection.setRequestProperty("content-Length", String.valueOf(data.length)); connection.setRequestProperty("data", params); // 发送数据 OutputStream out = connection.getOutputStream(); out.write(data); out.flush(); out.close(); // 接收反馈 if(connection.getResponseCode() == 200){ InputStream in = connection.getInputStream(); // 流 -> 字符串 ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = -1; while((len = in.read(buf)) != -1){ baos.write(buf, 0, len); } String resule = new String(baos.toByteArray(), "utf8"); if(!"".equals(resule)){ System.out.println(resule); } baos.close(); in.close(); } } catch (Exception e) { e.printStackTrace(); } }
当然,Post请求也支持Get的参数拼接,它比较复杂,暂时只整理将数据放在头报文的方式来发送数据。
1.5、 服务端代码
public class RequestDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解决编码问题 response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); // 获取到账号和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); PrintWriter out = response.getWriter(); if(username != null && password != null){ // 验证账号和密码 if(username.equals(password)){ System.out.println(username + "#" + password); out.print("登录成功!"); }else { out.print("登录失败!"); } }else{ System.out.println("账号密码为空!"); } out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 得到请求头的name集合 ServletOutputStream out = response.getOutputStream(); Enumeration<String> em = request.getHeaderNames(); while (em.hasMoreElements()) { String name = (String) em.nextElement(); if("data".equals(name)){ // 接收到发送过来的数据 String value = request.getHeader(name); System.out.println(value); out.print(value); } } } }
Demo下载地址:链接:http://pan.baidu.com/s/1gfvzzKf 密码:8vaf
1.6、总结
1.HttpURLConnection的connect()函数实际上只是建立一个与服务器的tcp链接,而没有实际发送http请求。无论是post还是get请求,http请求实际上直到
HttpURKConnection的getInputStream()方法时才正式发送出去。
2.用Post方式发送URL请求时,set函数都必须在connect()函数执行前完成。而对于outpustStream的写操作必须在InputStream的读操作之前。否则抛出异常。
3.http请求由两部分组成:http头和正文,connect()函数会根据HttpURLConnection对象配置值生成http头部信息,所以调用connect函数前,就必须把所有配置准备好。
二、HttpClient
HttpClient是apache开源组织研发的一个API,被Android引入使用。(URL以及HttpUrlConnection是java自带的API)。HttpClient设计的思想是模拟浏览器的操作来实现网络访问。
使用步骤:
· 定义一个客户端对象:即获得一个HttpClient对象(打开浏览器)
· 定义请求方法(输入网址):Get——HttpGet/POST——HttpPost
· 设置请求的参数/请求头信息/连接超时时间/读取数据超时时间等
· 执行请求(敲回车):execute方法——此方法会返回一个HttpResponse对象
· 获取状态码:response.getStatusLine().getStatusCode()
· 若状态码是200,获取服务器返回的数据:
InputStream is=response.getEntity().getContent();
· 操作结束后断开连接
client.getConnectionManager().shutdown();
1.1、Get请求
1.2、Post请求
三、Xutils
1.1、xUtils简介
xUtils 包含了很多实用的android工具。
xUtils 最初源于Afinal框架,进行了大量重构,使得xUtils支持大文件上传,全面的http请求协议支持(10种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆响
xUitls最低兼容android 2.2 (api level 8)
1.2、四大模块
1、Httputils模块
•支持同步,异步方式的请求;
•支持大文件上传,上传大文件不会oom;
•支持GET,POST,PUT,MOVE,COPY,DELETE,HEAD,OPTIONS,TRACE,CONNECT请求;
•下载支持301/302重定向,支持设置是否根据Content-Disposition重命名下载的文件;
•返回文本内容的请求(默认只启用了GET请求)支持缓存,可设置默认过期时间和针对当前请求的过期时间。
2、DbUtils模块
•android中的orm框架,一行代码就可以进行增删改查;
•支持事务,默认关闭;
•可通过注解自定义表名,列名,外键,唯一性约束,NOT NULL约束,CHECK约束等(需要混淆的时候请注解表名和列名);
•支持绑定外键,保存实体时外键关联实体自动保存或更新;
•自动加载外键关联实体,支持延时加载;
•支持链式表达查询,更直观的查询语义,参考下面的介绍或sample中的例子
3、ViewUtils模块
•android中的ioc框架,完全注解方式就可以进行UI,资源和事件绑定;
•新的事件绑定方式,使用混淆工具混淆后仍可正常工作;
•目前支持常用的20种事件绑定,参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event。
4、BitmapUtils模块
•加载bitmap的时候无需考虑bitmap加载过程中出现的oom和android容器快速滑动时候出现的图片错位等现象;
•支持加载网络图片和本地图片;
•内存管理使用lru算法,更好的管理bitmap内存;
•可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等...
1.3、权限和混淆
1、权限设置
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2、混淆注意
添加Android默认混淆配置${sdk.dir}/tools/proguard/proguard-android.txt
不要混淆xUtils中的注解类型,添加混淆配置:-keep class * extends java.lang.annotation.Annotation { *; }
对使用DbUtils模块持久化的实体类不要混淆,或者注解所有表和列名称@Table(name="xxx"),@Id(column="xxx"),@Column(column="xxx"),@Foreign(column="xxx",foreign="xxx");
1.4、HttpUtils使用
1、普通get方法
HttpUtils http = new HttpUtils(); http.send(HttpRequest.HttpMethod.GET, "http://www.lidroid.com", new RequestCallBack<String>(){ @Override public void onLoading(long total, long current, boolean isUploading) { testTextView.setText(current + "/" + total); } @Override public void onSuccess(ResponseInfo<String> responseInfo) { textView.setText(responseInfo.result); } @Override public void onStart() { } @Override public void onFailure(HttpException error, String msg) { } });
2、提交和上传
RequestParams params = new RequestParams(); params.addHeader("name", "value"); // 拼接到url(get方法),和addBodyParamer可以任选其一 params.addQueryStringParameter("name", "value"); // 只包含字符串参数时默认使用BodyParamsEntity, // 类似于UrlEncodedFormEntity("application/x-www-form-urlencoded")。 params.addBodyParameter("name", "value"); // 加入文件参数后默认使用MultipartEntity("multipart/form-data"), // 如需"multipart/related",xUtils中提供的MultipartEntity支持设置subType为"related"。 // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity(如: // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity)。 // 例如发送json参数:params.setBodyEntity(new StringEntity(jsonStr,charset)); params.addBodyParameter("file", new File("path")); ... HttpUtils http = new HttpUtils(); http.send(HttpRequest.HttpMethod.POST,"uploadUrl....",params,new RequestCallBack<String>() { @Override public void onStart() { testTextView.setText("conn..."); } @Override public void onLoading(long total, long current, boolean isUploading) { if (isUploading) { testTextView.setText("upload: " + current + "/" + total); } else { testTextView.setText("reply: " + current + "/" + total); } } @Override public void onSuccess(ResponseInfo<String> responseInfo) { testTextView.setText("reply: " + responseInfo.result); } @Override public void onFailure(HttpException error, String msg) { testTextView.setText(error.getExceptionCode() + ":" + msg); } });
3、下载文件
支持断点续传,随时停止下载任务,开始任务...
HttpUtils http = new HttpUtils(); HttpHandler handler = http.download("http://apache.dataguru.cn/httpcomponents/httpclient/source/httpcomponents-client-4.2.5-src.zip", "/sdcard/httpcomponents-client-4.2.5-src.zip", true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。 true, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。 new RequestCallBack<File>() { @Override public void onStart() { testTextView.setText("conn..."); } @Override public void onLoading(long total, long current, boolean isUploading) { testTextView.setText(current + "/" + total); } @Override public void onSuccess(ResponseInfo<File> responseInfo) { testTextView.setText("downloaded:" + responseInfo.result.getPath()); } @Override public void onFailure(HttpException error, String msg) { testTextView.setText(msg); } }); ... //调用cancel()方法停止下载 handler.cancel();
1.5、DbUtils使用
DbUtils db = DbUtils.create(this); User user = new User(); //这里需要注意的是User对象必须有id属性,或者有通过@ID注解的属性 user.setEmail("wyouflf@qq.com"); user.setName("wyouflf"); db.save(user); // 使用saveBindingId保存实体时会为实体的id赋值 ... // 查找 Parent entity = db.findById(Parent.class, parent.getId()); List<Parent> list = db.findAll(Parent.class);//通过类型查找 Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=","test")); // IS NULL Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=", null)); // IS NOT NULL Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","!=", null)); // WHERE id<54 AND (age>20 OR age<30) ORDER BY id LIMIT pageSize OFFSET pageOffset List<Parent> list = db.findAll(Selector.from(Parent.class) .where("id" ,"<", 54) .and(WhereBuilder.b("age", ">", 20).or("age", " < ", 30)) .orderBy("id") .limit(pageSize) .offset(pageSize * pageIndex)); // op为"in"时,最后一个参数必须是数组或Iterable的实现类(例如List等) Parent test = db.findFirst(Selector.from(Parent.class).where("id", "in", new int[]{1, 2, 3})); // op为"between"时,最后一个参数必须是数组或Iterable的实现类(例如List等) Parent test = db.findFirst(Selector.from(Parent.class).where("id", "between", new String[]{"1", "5"})); DbModel dbModel = db.findDbModelAll(Selector.from(Parent.class).select("name"));//select("name")只取出name列 List<DbModel> dbModels = db.findDbModelAll(Selector.from(Parent.class).groupBy("name").select("name", "count(name)")); ... List<DbModel> dbModels = db.findDbModelAll(sql); // 自定义sql查询 db.execNonQuery(sql) // 执行自定义sql ...
1.6、ViewUtils使用
完全注解方式可以进行UI绑定和事件绑定,无需findViewById和setClickListener等。
// xUtils的view注解要求必须提供id,以使代码混淆不受影响。 @ViewInject(R.id.textView) TextView textView; //@ViewInject(vale=R.id.textView, parentId=R.id.parentView) //TextView textView; @ResInject(id = R.string.label, type = ResType.String) private String label; // 取消了之前使用方法名绑定事件的方式,使用id绑定不受混淆影响 // 支持绑定多个id @OnClick({R.id.id1, R.id.id2, R.id.id3}) // or @OnClick(value={R.id.id1, R.id.id2, R.id.id3}, parentId={R.id.pid1, R.id.pid2, R.id.pid3}) // 更多事件支持参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event。 @OnClick(R.id.test_button) public void testButtonClick(View v) { // 方法签名必须和接口中的要求一致 ... } ... //在Activity中注入: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ViewUtils.inject(this); //注入view和事件 ... textView.setText("some text..."); ... } //在Fragment中注入: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.bitmap_fragment, container, false); // 加载fragment布局 ViewUtils.inject(this, view); //注入view和事件 ... } //在PreferenceFragment中注入: public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ViewUtils.inject(this, getPreferenceScreen()); //注入view和事件 ... } // 其他重载 // inject(View view); // inject(Activity activity) // inject(PreferenceActivity preferenceActivity) // inject(Object handler, View view) // inject(Object handler, Activity activity) // inject(Object handler, PreferenceGroup preferenceGroup) // inject(Object handler, PreferenceActivity preferenceActivity)
1.7、BitmapUtils使用
BitmapUtils bitmapUtils = new BitmapUtils(this); // 加载网络图片 bitmapUtils.display(testImageView, "http://bbs.lidroid.com/static/image/common/logo.png"); // 加载本地图片(路径以/开头, 绝对路径) bitmapUtils.display(testImageView, "/sdcard/test.jpg"); // 加载assets中的图片(路径以assets开头) bitmapUtils.display(testImageView, "assets/img/wallpaper.jpg"); // 使用ListView等容器展示图片时可通过PauseOnScrollListener控制滑动和快速滑动过程中时候暂停加载图片 listView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true)); listView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true, customListener));
1.8、LogUtils使用
// 自动添加TAG,格式: className.methodName(L:lineNumber) // 可设置全局的LogUtils.allowD = false,LogUtils.allowI = false...,控制是否输出log。 // 自定义log输出LogUtils.customLogger = new xxxLogger(); LogUtils.d("wyouflf");
源码下载:
链接:http://pan.baidu.com/s/1miKW9FM 密码:u88h