1.回顾
上篇 学习了AsyncTask 的相关知识
2.重点
(1)URLConnection(GET) 数据请求,图片请求 封装;
(2)URLConnection(POST)图片上传,数据上传,图片和数据同时上传 封装;
3. URLConnection(GET) 数据请求,图片请求 封装;
3.1 解释
数据请求,可以返回 JSON 字符串等数据;
图片请求,返回 Bitmap 数据;
3.2 实现
(1)其中 请求的图片 如果 比较大的话,在 给 ImageView 的时候,会出 内存溢出 错误;
(2)故 在 这里 进行 图片 质量压缩;(Android实现图片选择和图片压缩);
(3)或者 图片压缩工具类 下载;
package com.example.Http;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class UrlConnGetdata {
/**
* 加载数据
* @param urlpath
* @return
*/
public static String getData(String urlpath) {
String result = "getData() 出错了";
try {
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setUseCaches(false);
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
isr.close();
result = buffer.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
result += e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
result += e.getMessage();
}
return result;
}
/**
* 加载单张图片
* @return
*/
public static Bitmap getBitmap(String imgPath){
try {
URL url=new URL(imgPath);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setUseCaches(false);
InputStream is=conn.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(is);
//质量压缩
//bitmap=PictureUtil.compressImage(bitmap);
return bitmap;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
3.3 调用
String result = UrlConnGetdata.getData(url);
Bitmap bitmap = UrlConnGetdata.getBitmap(url);
4.URLConnection(POST)图片上传,数据上传,图片和数据同时上传 封装;
4.1 基本思路
模仿着 web 表单提交实现 ,进行了封装,只需要 传图片信息参数 和 数据信息参数 即可;
4.2 实现
package com.example.Http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import android.util.Log;
public class UrlConnPostdata {
/**
* 表单参数
*/
private final static String LINEND = "\r\n";
private final static String BOUNDARY = "---------------------------7df2ad12508cc"; // 数据分隔线
private final static String PREFIX = "--";
private final static String MUTIPART_FORMDATA = "multipart/form-data";
private final static String CHARSET = "utf-8";
private final static String CONTENTTYPE = "application/octet-stream";
/**
* 表单数据
*/
// 提交地址
private String url;
// 提交参数
private Map<String, String> params = new HashMap<String, String>();
// 提交的图片信息:文件名和地址
private Map<String, String> filepaths = new HashMap<String, String>();
/**
* 1:上传图片 + 表单信息
*
* @param url
* 上传地址
* @param cparams
* 上传表单数据:Map中的key 为 表单中的 name值 ; value 为 表单中的 value值 没有为null
* @param cfilepaths
* 上传的文件地址; 单张图片上传,也需要使用 集合实现; 没有为null
*/
public UrlConnPostdata(String url, Map<String, String> cparams,
Map<String, String> cfilepaths) {
// 构造函数 初始化 参数
if (cfilepaths != null) {
this.filepaths.putAll(cfilepaths);
}
this.url = url;
if (cparams != null) {
this.params.putAll(cparams);
}
}
/**
* 程序入口
*/
public String connPost() {
boolean isupdata = isUploadData();
boolean isupimg = isUploadImage();
System.out.println("isupdata:" + isupdata + " isupimg:" + isupimg);
System.out.println("filepaths:" + filepaths.toString());
if (isupdata == false && isupimg == false) {
return "对不起,你的参数都没有值!";
} else {
// 执行上传
return postData(isupimg, isupdata);
}
}
/**
* 根据 params 的 数据 判断 是否 上传表单
*
* @return
*/
private boolean isUploadData() {
return params.size() > 0 ? true : false;
}
/**
* 根据 filepaths的 数据 判断是否上传图片
*
* @return
*/
private boolean isUploadImage() {
return filepaths.size() > 0 ? true : false;
}
/**
* HTTP上传 表单数据和图片表单数据
*
* @param isupimg
* 是否上传 表单数据
* @param isupdata
* 是否上传 图片数据
* @return
*/
private String postData(boolean isupimg, boolean isupdata) {
String flag = "上传失败";
Log.i("post-------------", "postfile");
HttpURLConnection urlConn = null;
BufferedReader br = null;
try {
// 新建url对象
URL url = new URL(this.url);
// 通过HttpURLConnection对象,向网络地址发送请求
urlConn = (HttpURLConnection) url.openConnection();
// 设置该连接允许读取
urlConn.setDoOutput(true);
// 设置该连接允许写入
urlConn.setDoInput(true);
// 设置不能适用缓存
urlConn.setUseCaches(false);
// 设置连接超时时间
urlConn.setConnectTimeout(3000); // 设置连接超时时间
// 设置读取时间
urlConn.setReadTimeout(4000); // 读取超时
// 设置连接方法post
urlConn.setRequestMethod("POST");
// 设置文件字符集
urlConn.setRequestProperty("Charset", CHARSET);
// 设置维持长连接
urlConn.setRequestProperty("connection", "Keep-Alive");
// 设置文件类型
urlConn.setRequestProperty("Content-Type", MUTIPART_FORMDATA
+ ";boundary=" + BOUNDARY);
DataOutputStream dos = new DataOutputStream(
urlConn.getOutputStream());
// 构建表单数据
if (isupdata) {
String entryText = GetParamsFormData();
dos.write(entryText.getBytes());
}
// 构建图片表单数据
if (isupimg) {
Set<String> keys = filepaths.keySet();
for (String key : keys) {
StringBuffer sb = new StringBuffer("");
sb.append(PREFIX + BOUNDARY + LINEND)
.append("Content-Disposition: form-data;"
+ " name=\"" + key + "\";" + " filename=\""
+ filepaths.get(key) + "\"" + LINEND)
.append("Content-Type:" + CONTENTTYPE + ";"
+ "charset=" + CHARSET + LINEND)
.append(LINEND);
dos.write(sb.toString().getBytes());
FileInputStream fis = new FileInputStream(new File(
filepaths.get(key)));
byte[] buffer = new byte[10000];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
dos.write(buffer, 0, len);
}
dos.write(LINEND.getBytes());
fis.close();
}
}
// 请求的结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
dos.write(end_data);
dos.flush();
dos.close();
// 发送请求数据结束
// 接收返回信息
int code = urlConn.getResponseCode();
if (code != 200) {
urlConn.disconnect();
} else {
br = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
String result = "";
String line = null;
while ((line = br.readLine()) != null) {
result += line;
}
Log.i("post-------------", result);
flag = result;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("--------上传图片错误--------", e.getMessage());
flag += e.getMessage();
} finally {
try {
if (br != null) {
br.close();
}
if (urlConn != null) {
urlConn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 表单数据封装
*
* @return
* @throws Exception
*/
private String GetParamsFormData() {
StringBuffer buffer = new StringBuffer();
if (isUploadData()) {
Set<String> keys = params.keySet();
for (String key : keys) {
StringBuffer sb = new StringBuffer();
sb.append(PREFIX + BOUNDARY + LINEND)
.append("Content-Disposition: form-data;" + " name=\""
+ key + "\"" + LINEND).append(LINEND)
.append(params.get(key) + LINEND);
buffer.append(sb.toString());
}
} else {
buffer.append("GetParamsFormData()没有数据");
}
System.out.println(buffer.toString());
return buffer.toString();
}
}
4.3 调用
参数1:地址
参数2:数据参数 Map<String,String> 类型 ; key 为 表单中的 name值 ,value为 表单中的value
参数3:图片参数 Map<String,String> 类型 ; key 为 表单中的 name值 ,value 为 图片路径
(1)仅仅上传 数据参数
String url = "http://192.168.75.1:8080/UploadEmo/UploadImage";
UrlConnPostdata postdata = new UrlConnPostdata(url, Map<String,String> null);
String result = postdata.connPost();
(2)仅仅上传 图片
String url = "http://192.168.75.1:8080/UploadEmo/UploadImage";
UrlConnPostdata postdata = new UrlConnPostdata(url, null, Map<String,String>);
String result = postdata.connPost();
(3)同时上传图片和数据
String url = "http://192.168.75.1:8080/UploadEmo/UploadImage";
UrlConnPostdata postdata = new UrlConnPostdata(url, params[0],
params[1]);
String result = postdata.connPost();
5. URLConnction 封装类 免积分下载
http://download.csdn.net/detail/lablenet/9081011