android 请求网络 和 httpclient的使用上传下载
访问网络最主要的也就是 http协议了。
http协议很简单,但是很重要。
直接上代码了,里面都是1个代码块 代码块的,用哪一部分直接拷出去用就好了。
1.访问网络用 get 和 post 自己组拼提交参数 ,httpclient 方式提交
2.上传 和 下载
3.比如访问服务器后 返回来的 xml 和 json 的简单解析方法
String path = "http://192.168.13.1";
String username ="ll";
String pwd="123"; /** get 组拼 */
public void httpGet()
throws Exception { String param1 = URLEncoder.encode(username);
String param2 = URLEncoder.encode(pwd);
URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
// 数据并没有发送给服务器
// 获取服务器返回的流信息
InputStream in = conn.getInputStream();
byte[] result = StreamTool.getBytes(in); //return new String(result);
} /** post 组拼 */
public void httpPost() throws Exception { URL url = new URL(path);
String param1 = URLEncoder.encode(username);
String param2 = URLEncoder.encode(pwd);
//开始连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = "username=" + param1 + "&password=" + param2;
//设置方式 post
conn.setRequestMethod("POST");
//timeout 5000
conn.setConnectTimeout(5000);
// 设置 http协议可以向服务器写数据
conn.setDoOutput(true);
// 设置http协议的消息头
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length()));
// 把我们准备好的data数据写给服务器
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
// httpurlconnection 底层实现 outputstream 是一个缓冲输出流
// 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
String ss= new String(result);
} } /** httpclient get */
public void httpClentGet () throws Exception{
//获取到一个浏览器的实例
HttpClient client = new DefaultHttpClient();
//准备请求的地址
String param1 = URLEncoder.encode(username);
String param2 = URLEncoder.encode(pwd);
HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
//敲回车 发请求
HttpResponse ressponse = client.execute(httpGet);
int code = ressponse.getStatusLine().getStatusCode();
if( code == 200){
InputStream is =ressponse.getEntity().getContent();
//byte[] result = StreamTool.getBytes(is); } } // 不需要的时候关闭 httpclient client.getConnectionManager().shutdown();
/** httpclient post **/
public void httpClentPost() throws Exception{
//1. 获取到一个浏览器的实例
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(path);
// 键值对 BasicNameValuePair
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("pwd", pwd));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//3.设置post请求的数据实体
httppost.setEntity(entity);
//4. 发送数据给服务器
HttpResponse ressponse = client.execute(httppost);
int code = ressponse.getStatusLine().getStatusCode();
if(code == 200){
InputStream is =ressponse.getEntity().getContent();
byte[] result = StreamTool.getBytes(is); //return new String(result);
} } /*** 下载一个东西 ***/
public void getFileData(Context context){ try {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
//执行
HttpResponse ressponse = client.execute(httpGet);
int code = ressponse.getStatusLine().getStatusCode(); if(code == HttpStatus.SC_OK){
InputStream in =ressponse.getEntity().getContent();
//图片
// Bitmap bitmap = BitmapFactory.decodeStream(in);
// in.close(); //文件什么的比如读取了是要写在本地的
//小文件直接读取 大文件读取一点写一点
//byte[] result = StreamTool.getBytes(in);
// //这里可以得到文件的类型 如image/jpg /zip /tiff 等等 但是发现并不是十分有效,有时明明后缀是.rar但是取到的是null,这点特别说明
System.out.println(ressponse.getEntity().getContentType());
//可以判断是否是文件数据流
System.out.println(ressponse.getEntity().isStreaming());
//设置本地保存的文件
//File storeFile = new File("c:/0431la.zip");
String path="sdcard/aa.txt";
FileOutputStream output = context.openFileOutput(path, context.MODE_PRIVATE);
//得到网络资源并写入文件
InputStream input = ressponse.getEntity().getContent();
byte b[] = new byte[1024];
int j = 0;
while( (j = input.read(b))!=-1){
output.write(b,0,j);
}
output.flush();
output.close();
}
} catch (Exception e) {
// TODO: handle exception
}
} /**
* 提交数据给服务器 带一个文件
* @param filepath 文件在手机上的路径
*/
public void PostData(String filepath) throws Exception{ // 实例化上传数据的 数组 part [] username pwd
Part[] parts = {
new StringPart("username", username),
new StringPart("pwd", pwd),
new FilePart("file", new File(filepath))
}; PostMethod file_Post = new PostMethod(path);
// 多种类型的数据实体
file_Post.setRequestEntity(new MultipartRequestEntity(parts, file_Post.getParams()));
//创建 client
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
//timeout
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
//执行
int status = client.executeMethod(file_Post); if(status==200){ } } //传送文件
public void setFile() throws Exception{ HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.1");
File file = new File(path);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // FileEntity entity = new FileEntity(file, "binary/octet-stream");
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost); if(response.getStatusLine().getStatusCode() == 200){ } } /** 1.
* 一般访问了就会返回来1个 webservice
* pull解析访问webservice 返回来的xml
* **/ public void pullJX(byte[] bb) throws Exception{
// byte[] bb = EntityUtils.toByteArray(response.getEntity());
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(new ByteArrayInputStream(bb), "UTF-8");
int event = pullParser.getEventType();
List<Object> info;
while(event != XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_DOCUMENT:
info = new ArrayList<Object>();
break; case XmlPullParser.START_TAG:
if("aa".equals(pullParser.getName())){
String id = pullParser.nextText().toString(); }
break; case XmlPullParser.END_TAG:
if("aa".equals(pullParser.getName())){
}
break;
}
event = pullParser.next();
}
} /**2.
* 解析 json 数据 [{id:"001",name:"lilei",age:"20"},{id:"002",name:"zhangjia",age:"30"}]
*/
private static List parseJSON(InputStream in) throws Exception{
byte[] data = StreamTool.getBytes(in);
String s =new String(data);
// 转换成 json 数组对象 [{"001","ll","20"},{"002","zj","30"},]
JSONArray json = new JSONArray(s);
for (int i = 0; i < json.length() ; i++) {
JSONObject j = json.getJSONObject(i);
String aa1 = j.getString("id");
String aa2 = j.getString("name");
String aa3 = j.getString("age");
}
return null;
}
HttpClient其实是一个interface类型,HttpClient封装了对象需要执行的Http请求、身份验证、连接管理和其它特性
HttpClient有三个已知的实现类分别是:
AbstractHttpClient, AndroidHttpClient, DefaultHttpClient
AndroidHttpClient是对HttpClient的包装,内部带访问连接器,并设置为可以多线程使用,
public class MyApplication extends Application{
private AndroidHttpClient httpClient;
// application oncreate的时候创建
public void onCreate(){
super.onCreate();
httpClient = AndroidHttpClient.newInstance("Android");
}
//供外部调用
public AndroidHttpClient getHttpClient() {
if (httpClient == null){
httpClient = AndroidHttpClient.newInstance("Android");
}
return httpClient;
}
@Override
public void onLowMemory() {
super.onLowMemory();
shutdownHttpClient();
}
@Override
public void onTerminate() {
super.onTerminate();
shutdownHttpClient();
}
//关闭
private void shutdownHttpClient() {
if (httpClient != null) {
if (httpClient.getConnectionManager() != null) {
httpClient.getConnectionManager().shutdown();
}
httpClient.close();
httpClient = null;
}
}
}
外部调用的话
AndroidHttpClient httpClient = ((MyApplication)getApplication()).getHttpClient();
android 请求网络 和 httpclient的使用上传下载的更多相关文章
- Android使用OkHttp实现带进度的上传下载
先贴上MainActivity.java package cn.edu.zafu.sample; import android.os.Bundle; import android.support.v7 ...
- Android Studio中不能显示svn的上传下载两个图标同时version control为灰,不可点击
最近在接触Android Studio,涉及到svn的配置,因为是先安装的svn,后安装的Android Studio,后边同事告诉我, Android Studio 的SVN安装与其他IDE有很大差 ...
- Android利用网络编程HttpClient批量上传(一个)
请尊重他人的劳动成果.转载请注明出处:Android网络编程之使用HttpClient批量上传文件 我曾在<Android网络编程之使用HTTP訪问网络资源>一文中介绍过HttpCient ...
- Android利用网络编程HttpClient批量上传(两)AsyncTask+HttpClient监测进展情况,并上传
请尊重别人的劳动.转载请注明出处: Android网络编程之使用HttpClient批量上传文件(二)AsyncTask+HttpClient并实现上传进度监听 执行效果图: 我曾在<Andro ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- Android开发中使用七牛云存储进行图片上传下载
Android开发中的图片存储本来就是比较耗时耗地的事情,而使用第三方的七牛云,便可以很好的解决这些后顾之忧,最近我也是在学习七牛的SDK,将使用过程在这记录下来,方便以后使用. 先说一下七牛云的存储 ...
- 一个linux下简单的纯C++实现Http请求类(GET,POST,上传,下载)
目录 一个linux下简单的纯C++实现Http请求类(GET,POST,上传,下载) Http协议简述 HttpRequest类设计 请求部分 接收部分 关于上传和下载 Cpp实现 关于源码中的Lo ...
- Android 本地tomcat服务器接收处理手机上传的数据之案例演示
上一篇:Android 本地tomcat服务器接收处理手机上传的数据之环境搭建 本篇基于上一篇搭建的服务器端环境,具体介绍Android真机上传数据到tomcat服务器的交互过程 场景:A ...
- Android+Spring Boot 选择+上传+下载文件
2021.02.03更新 1 概述 前端Android,上传与下载文件,使用OkHttp处理请求,后端使用Spring Boot,处理Android发送来的上传与下载请求.这个其实不难,就是特别多奇奇 ...
随机推荐
- 腾讯QQ:异地登陆也被封号,你们是怎么决策的???
此文我想放到首页,让很多其它的人看到,更期待有人能解释一下.希望管理员给开绿灯. 今天真是费解,我的手机号是青岛的.可是我在武汉工作,因为是3G的卡,全国没有漫游,打电话也没多少钱,所以就没换号. 谁 ...
- UE-9260使用说明1
UE-9260使用说明 序号 版本号 日期 备注 1 V0.1 2015-03-21 原始版本号.作者:xiaobin 2 3 4 5 主机环境 1.烧写操作 仿真器和FTP烧写 OS: Win XP ...
- Excel自己定义纸张打印设置碰到无法对上尺寸的问题
作者:iamlaosong 据操作人员反映.自己定义纸张设置无论用,打印时每页表头都会下移,非常快就跑偏到下涨纸了. 打印机是针打,齿轮进纸.应该非常精确的.初步怀疑纸张尺寸量的有问题,建议其多量几页 ...
- 将EC2里的实例导出到RAW文件并进行修改
你可能有自己的instance在amazon云环境里面,或者是你想深度修改一下marketplace里面提供的那些系统又估计运行中的instance改动不方便 亚马逊作为云计算领域的大哥大,我不得不说 ...
- 初探 FFT/DFT
有用的学习链接&书籍 傅立叶变化-维基百科 离散傅立叶变化-维基百科·长整数与多项式乘法 维基百科看英文的更多内容&有趣的图 快速傅立叶变化-百度百科,注意其中的图! 组合数学(第4版 ...
- Amlogic开关机按键功能实现
在做AMlogic项目的时候,配置按键后,发现电源键仅仅能关机,不能开机,非常是郁闷 后来发现是漏掉了一个地方没有配置,firmware/arc_power/irremote2arc.c 这个文件中面 ...
- jquery mobile自己定义webapp开发实例(一)——前言篇
用jquery mobile做了一段时间的webapp开发,准备用自己的一个小demo做一个模块化的分享 点击demo演示 手机演示二维码: 此demo已经是比較老的版本号,用户体验流畅度确实还存在非 ...
- webstorm入门1-主题和配色
1.引子 以前介绍过 Sublime text 3 系列的文章,着重介绍了 Sublime text 3 如何下载.安装.插件.配置等内容.Sublime text 3的轻量和富扩展,为前端开发带来了 ...
- web攻击方式和防御方法
在http请求报文中载入攻击代码,就能发起对web应用的攻击.通过url查询字段或者表单.http首部.cookie等途径吧攻击代码传入,若这时web应用存在安全漏洞,那内部信息就会遭到窃取! 对we ...
- swift-var/let定义变量和常量
// Playground - noun: a place where people can play import UIKit //--------------------------------- ...