Android网络请求操作httpurlconnection和httpclient基本使用
1. 网络请求操作中Get请求和Post请求有什么区别?
1) Get是向服务器发索取数据的一种请求,而Post是向服务器提交数据的一种请求
2) Get是获取信息,而不是修改信息,类似数据库查询功能一样,数据不会被修改
3) 对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据
4) get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB
5) Get请求的参数会跟在url后进行传递,请求的数据会附在URL之后,以?分割URL和传输数据,参数之间以&相连,%XX中的XX为该符号以16进制表示的ASCII,如果数据是英文字母/数字,原样发送,如果是空格,转换为+,如果是中文/其他字符,则直接把字符串用BASE64加密, get安全性非常低,post安全性较高
2. http请求返回状态码
状态码 |
含义 |
100~199 |
表示成功接收请求,要求客户端继续提交下一次请求才能完成整个处理过程 |
200~299 |
表示成功接收请求并已完成整个处理过程 |
300~399 |
为完成请求,客户需进一步细化请求。例如,请求的资源已经移动一个新地址 |
400~499 |
客户端的请求有错误 |
500~599 |
服务器端出现错误 |
常用状态码:
200(正常):表示一切正常,返回的是正常请求结果
302/307(临时重定向):指出被请求的文档已被临时移动到别处,此文档的新的URL 在Location响应头中给出。
304(未修改):表示客户机缓存的版本是最新的,客户机可以继续使用它,无需到服务 器请求。
404(找不到):服务器上不存在客户机所请求的资源。
500(服务器内部错误):服务器端的程序发生错
3. httpurlconnection基本用法
1) 基本的Get请求
try {String url = "http://apis.juhe.cn/mobile/get" + "?phone=" + URLEncoder.encode("13429667914", "utf-8")+ "&key=" + "3a0152ec37d15dee57b380669fe714a2";URL url1 = new URL(url);HttpURLConnection urlConn = (HttpURLConnection) url1.openConnection();urlConn.setRequestProperty("content-type", "application/json");urlConn.setDoInput(true);urlConn.setDoOutput(true);urlConn.setConnectTimeout(5 * 1000);// 设置请求方式为 PUTurlConn.setRequestMethod("GET");urlConn.setRequestProperty("Charset", "UTF-8");Log.i("888", "" + urlConn.getResponseCode());if (urlConn.getResponseCode() == 200) {BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));String str;StringBuffer sb = new StringBuffer();while ((str = reader.readLine()) != null) {sb.append(str);}Log.i("esasdasd", "result:" + sb.toString());Message message = new Message();message.what = 111;message.obj = sb.toString();handler.sendMessage(message);urlConn.disconnect();}} catch (Exception e) {e.printStackTrace();}
2) 基本的Post请求
URL url1 = null; try { url1 = new URL(http://192.168.2.69:8888/user/sign-in?ds=mobile); } catch (MalformedURLException e) { e.printStackTrace(); } if (url1 != null) { try { HttpURLConnection urlConn = (HttpURLConnection) url1.openConnection(); urlConn.setRequestProperty("content-type", "application/json"); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setConnectTimeout(5 * 1000); //设置请求方式为 PUT urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "application/json"); urlConn.setRequestProperty("Accept", "application/json"); urlConn.setRequestProperty("Charset", "UTF-8"); DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); //写入请求参数 JSONObject jsonObject = new JSONObject();jsonObject.put("username", "username");jsonObject.put("email", "email");jsonObject.put("password", "password");dos.writeBytes(jsonObject.toString()); dos.flush(); dos.close(); Log.i("888", ""+urlConn.getResponseCode());if (urlConn.getResponseCode() == 200) { // 请求返回的数据InputStream in = urlConn.getInputStream();String a = null;try {byte[] data1 = new byte[in.available()];in.read(data1);// 转成字符串a = new String(data1);System.out.println(a);final StringBuffer sb = new StringBuffer(a);handler.post(new Runnable() {@Overridepublic void run() {List<Register_name> list=parseJson(sb.toString());Message message=new Message();message.obj=list;handler.sendMessage(message);}});} catch (Exception e1) {e1.printStackTrace();}urlConn.disconnect(); } } catch (Exception e) { e.printStackTrace(); } }
4. HttpclientGet请求基本使用
1) client = new DefaultHttpClient();// 保持和服务器登录状态一直是登录着的,必不可少设置全局唯一的Cookie((AbstractHttpClient) client).setCookieStore(FirstActivity.cookieStore);HttpGet post = new HttpGet(url);post.addHeader("contentType", "application/json");try {postResp = client.execute(post);int return_code = postResp.getStatusLine().getStatusCode();if (return_code == 200) {final String recives = EntityUtils.toString(postResp.getEntity());Log.d("recives", recives);handler.post(new Runnable() {@Overridepublic void run() {Message message = new Message();message.what = 222;message.obj = recives.toString();handler.sendMessage(message);}});} else if (return_code == 400) {Log.d("recives", "error" + return_code);} else {Log.d("recives", "error" + return_code);}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
2) Post基本使用
client = new DefaultHttpClient();// 保持和服务器登录状态一直是登录着的,必不可少设置全局唯一的Cookie((AbstractHttpClient) client).setCookieStore(FirstActivity.cookieStore);HttpPost post = new HttpPost(url);post.addHeader("contentType", "application/json");try {JSONObject jsonObject = new JSONObject();jsonObject.put("username", "username");jsonObject.put("email", "username");jsonObject.put("password", "password");post.setEntity(new StringEntity(jsonObject.toString(), "utf-8"));postResp = client.execute(post);int return_code = postResp.getStatusLine().getStatusCode();if (return_code == 200) {final String recives = EntityUtils.toString(postResp.getEntity());Log.d("recives", recives);handler.post(new Runnable() {@Overridepublic void run() {Message message = new Message();message.what=222;message.obj = recives.toString();handler.sendMessage(message);}});} else if (return_code == 400) { Log.d("recives", "error"+return_code);} else {Log.d("recives", "error"+return_code);}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
5. 代码缺少的部分
URL url1 = null; private HttpClient client;HttpResponse postResp;private final static BasicCookieStore cookieStore = new BasicCookieStore();Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 111:String string=(String) msg.obj;Toast.makeText(FirstActivity.this, string, Toast.LENGTH_SHORT).show();break;case 222:String string1=(String) msg.obj;Toast.makeText(FirstActivity.this, string1, Toast.LENGTH_SHORT).show();break;default:break;}super.handleMessage(msg);}};
6. 补充的部分
1.// 保持和服务器登录状态一直是登录着的,必不可少设置全局唯一的Cookie
((AbstractHttpClient) client).setCookieStore(LoginHttpThread.cookieStore);
2.后续会继续补充
Android网络请求操作httpurlconnection和httpclient基本使用相关推荐
- Android网络请求归纳 HttpUrlConnection| Vollety|OKHttp3|Retrofit2
1.网络基础知识: Android网络API库有哪些? HttpUrlConnection: jdk内置 HttpClient:android提供,6.0被删除 Voll ...
- Android 网络请求详解
我们知道大多数的 Android 应用程序都是通过和服务器进行交互来获取数据的.如果使用 HTTP 协议来发送和接收网络数据,就免不了使用 HttpURLConnection 和 HttpClient ...
- Android -- 网络请求
一. HttpURLConnection 二. HttpClient 三.Volley 四.OkHttp 五. Retrofit ----------------------------------- ...
- okhttp的应用详解与源码解析--android网络请求框架发展史
乘5G之势,借物联网之风,Android未来亦可期,Android优势在于开放,手机.平板.车载设备.智能家居等都是Android的舞台,Google不倒,Android不灭,本专栏的同步视频教程已经 ...
- android网络请求流程图,Android OKHttp系列1-流程总结
1. 调用示例 同步方式: new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = ...
- Android网络请求通信之Volley
一.Volley简介 Volley网络框架是Google公司在2013年发布的一款Android平台上的网络请求通信库.以下是对Volley的简单归纳. Volley的优点: 使网络通信更快.更简单. ...
- Android网络请求框架之Retrofit(二)
前面一篇文章介绍了Retrofit的基本用法,没有看过的童鞋可以移步:Android网络请求框架之Retrofit(一),现在我们来继续介绍Retrofit配合RxJava.RxAndroid的用法. ...
- Android 网络请求HttpURLConnection 和 HttpClient详解
Android一般通过http协议向服务端接口发送请求,常用有POST和GET传输方式.这种请求通常借助于HttpClient,HttpClient 是 Apache Jakarta Common 下 ...
- Android訪问网络,使用HttpURLConnection还是HttpClient?
原文地址:http://android-developers.blogspot.com/2011/09/androids-http-clients.html 大多数的Android应用程序都会使用HT ...
最新文章
- github绑定自己的域名
- OpenCV Shi-Tomasi corner 检测器
- Day 1 二分搜索训练总结
- 如何使用log4j记录日志
- 【转】eclipse中egit插件使用
- 第 5 章 File Share
- python编写交互界面查分_python小习题:查分数 - 李金龙
- 如何使用 ggplot2 ?
- Rust: 属性(attribute)的含义及文档大全
- c语言中 临时变量的作用,C语言 临时变量不能作为函数的返回值?
- 【谷粒商城】全网最全笔记(1/4)
- Qt基于FFmpeg解码本地视频生成RGB数据
- VBA每日一练(2),将txt 的部分/全部内容 导入到EXCEL
- 性能工具之stress工具使用教程(带源码说明)
- 计算机的外围设备找不到,bluetooth外围设备,教您bluetooth外围设备找不到驱动程序怎么解决...
- Python学习[4]:urllib库-爬虫的第三步之代理IP
- 如何进行高效学习——费曼技巧了解一下
- C++ 并发编程(C++11 到 C++17 )
- 3、Java 的变量和数据类型
- 普通话计算机等级用英语怎么说,普通话用英语怎么说
热门文章
- Java Heap dump文件分析工具jhat简介
- HDU 5445 Food Problem(多重背包)
- 【HTTP】989- HTTP 传输大文件的几种方案
- System.out.print(我爱你)
- Floyd最小环算法
- WebGl 球面计算公式
- JDBC编程(JDBC的使用)
- Android 10.0 行为变更(一)针对所有 API 级别的应用
- gre计算机科学,电子工程与计算机科学留学分享会(内含回顾实录+GRE福利包)...
- 2020 最新MySQL 安装及建议(小白操作)