InputStream和OutputStream
输入输出流在java中很常用,从文件读写到内存读写到网络通信都会用到。在之前的《 Android开发笔记(三十三)文本文件和图片文件的读写》中,我们学习了文件流FileOutputStream和FileInputStream,以及缓存流BufferedOutputStream和BufferedInputStream。这些输入输出流都继承自InputStream和OutputStream,下面是它们的常用方法:
InputStream的常用方法
available : 获取输入流的大小
read : 从输入流中读取数据
close : 关闭输入流
OutputStream的常用方法
write : 往输出流写数据
flush : 刷新输出流
close : 关闭输出流
java在进行http访问操作时,发送数据使用OutputStream,接收数据使用InputStream。如果采用HttpURLConnection,InputStream对象可从HttpURLConnection的getInputStream方法获得;如果采用HttpClient,InputStream对象可从HttpEntity的getContent方法获得。下面是http访问时与InputStream有关的加工操作:
1、从InputStream对象中读取字符串。首先把输入流的数据读到字节流ByteArrayOutputStream,然后调用字节流的toByteArray方法得到字节数组,最后调用String的构造函数根据指定编码从字节数组构造返回字符串;
2、从InputStream对象中读取图像。调用BitmapFactory的decodeStream方法即可返回Bitmap图像数据。
3、从InputStream对象中解压gzip压缩数据。引入GZIPInputStream从输入流构造解压流,然后再从解压流中读取数据。
HttpURLConnection
HttpURLConnection是java自带的http连接工具,属于轻量级,基本上使用该类就能打遍http,当然复杂点的功能(如分段传输、上传等等)得自己写代码细节。HttpURLConnection对象可从URL类的openConnection方法获得,下面是HttpURLConnection的常用方法:
setRequestMethod : 设置请求类型。GET表示get请求,POST表示post请求。
setConnectTimeout : 设置连接的超时时间。
setReadTimeout : 设置读取的超时时间。
setRequestProperty : 设置请求包头的字段。
setDoOutput : 设置是否允许发送数据。如果用到getOutputStream方法,则setDoOutput必须设置为true。
setDoInput : 设置是否允许接收数据。如果用到getInputStream方法,则setDoInput必须设置为true。
getOutputStream : 获取http输出流。调用该函数返回一个OutputStream对象,接着依次调用该对象的write和flush方法写入要发送的数据。
connect : 建立http连接。该方法在getOutputStream之后调用,在getInputStream之前调用。
getInputStream : 获取http输入流。调用该函数返回一个InputStream对象,接着调用该对象的read方法读出接收到的数据。
getResponseCode : 获取http返回码。
getHeaderField : 获取应答数据包头的指定字段值。
getHeaderFields : 获取应答数据包头的所有字段列表。
disconnect : 断开http连接。
HttpClient
HttpClient是Apache的http访问工具,属于重量级,封装了一些常用的处理工具如get请求工具HttpGet、post请求工具HttpPost、http响应工具HttpResponse、url编码表单工具UrlEncodedFormEntity、分段传输工具MultipartEntity等等。早期的Android同时包括Commons HttpClient (org.apache.commons.httpclient.*) 和 HttpComponents (org.apache.http.client.* ),后来就只内置后者了。即便是后者,Android也只内置了核心部分,开发中要想使用高级功能,还得引入httpmime和httpcore的jar包。
HttpGet和HttpPost分别用来处理get请求和post请求,两个类都继承自HttpRequestBase,而HttpRequestBase又继承自AbstractHttpMessage,下面是它们的常用方法:
构造函数 :
getMethod : 获取请求类型。
setHeader : 设置请求包头的字段值。无则添加,有则替换。
addHeader : 添加请求包头的字段值。不管原来有没有都予以添加,所以多次add会产生同名的重复字段。
setEntity : HttpPost专用,设置请求数据的包体。
设置超时时间要在HttpClient中直接设置,示例代码如下:
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
设置完毕HttpGet或者HttpPost,接着便是调用HttpClient的execute方法。该方法返回一个HttpResponse对象,下面是HttpResponse的常用方法:
getStatusLine : 获取http的处理结果。该方法返回一个StatusLine对象,要想获取状态码还得调用该对象的getStatusCode方法才行。
getHeaders : 获取应答的包头数据。
getEntity : 获取应答的包体数据。该方法返回一个HttpEntity对象,要想获取输入流还得调用该对象的getContent方法才行。
post方式发送的数据分两种,一种是表单数据,另一种是文件数据。表单数据的Content-Type为application/x-www-form-urlencoded,对应的处理类是UrlEncodedFormEntity;文件数据的Content-Type为multipart/form-data对应的处理类是MultipartEntityBuilder。这两个处理类都是从HttpEntity演化而来,其对象都作为setEntity方法的参数。
UrlEncodedFormEntity传入的是表单数据的键值对,构造函数的入参是键值对数组List<NameValuePair>,该数组的元素可添加BasicNameValuePair类型的对象。
MultipartEntityBuilder传入的是特殊的键值对,本质是按照分隔符分块传输,下面是它的常用方法:
create : 静态方法,创建一个MultipartEntityBuilder的实例。
setMode : 设置传输模式。一般是HttpMultipartMode.BROWSER_COMPATIBLE,这样可以更好的兼容不同浏览器。
setBoundary : 设置分隔符。
setCharset : 设置字符编码。
addPart : 添加一个分块。第一个参数是名称,第二个参数视情况如果是传输文本则为StringBody类型,如果是传输图片则为ByteArrayBody类型。
build : 建造并返回HttpEntity对象。
HTTP访问的额外处理
URL汉字编码
使用get方式传递请求数据,参数是放在url中直接送过去。如果参数值中有中文的,还得进行UTF8编码,比如“你”要转为“%E4%BD%A0”。下面是对url串进行转义与编码处理的代码示例:
import java.util.Locale;
import android.util.Log;
public class URLtoUTF8 {
private static final String TAG = "URLtoUTF8";
//转换为%E4%BD%A0形式
public static String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0;i < s.length();i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
}else {
byte[] b;
try {
b = String.valueOf(c).getBytes("utf-8");
}catch (Exception ex) {
Log.d(TAG, ex.toString());
b = new byte[0];
}
for (int j = 0;j < b.length;j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase(Locale.getDefault()));
}
}
}
return sb.toString();
}
//将%E4%BD%A0转换为汉字
public static String unescape(String s) {
StringBuffer sbuf = new StringBuffer();
int l = s.length();
int ch = -1;
int b, sumb = 0;
for (int i = 0, more = -1;i < l;i++) {
/* Get next byte b from URL segment s */
switch (ch = s.charAt(i)) {
case '%':
ch = s.charAt(++i);
int hb = (Character.isDigit((char) ch) ? ch - '0'
: 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
ch = s.charAt(++i);
int lb = (Character.isDigit((char) ch) ? ch - '0'
: 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
b = (hb << 4) | lb;
break;
case '+':
b = ' ';
break;
default:
b = ch;
}
/* Decode byte b as UTF-8, sumb collects incomplete chars */
if ((b & 0xc0) == 0x80) {// 10xxxxxx (continuation byte)
sumb = (sumb << 6) | (b & 0x3f);// Add 6 bits to sumb
if (--more == 0)
sbuf.append((char) sumb);// Add char to sbuf
}else if ((b & 0x80) == 0x00) {// 0xxxxxxx (yields 7 bits)
sbuf.append((char) b);// Store in sbuf
}else if ((b & 0xe0) == 0xc0) {// 110xxxxx (yields 5 bits)
sumb = b & 0x1f;
more = 1;// Expect 1 more byte
}else if ((b & 0xf0) == 0xe0) {// 1110xxxx (yields 4 bits)
sumb = b & 0x0f;
more = 2;// Expect 2 more bytes
}else if ((b & 0xf8) == 0xf0) {// 11110xxx (yields 3 bits)
sumb = b & 0x07;
more = 3;// Expect 3 more bytes
}else if ((b & 0xfc) == 0xf8) {// 111110xx (yields 2 bits)
sumb = b & 0x03;
more = 4;// Expect 4 more bytes
}else /*if ((b & 0xfe) == 0xfc)*/{// 1111110x (yields 1 bit)
sumb = b & 0x01;
more = 5;// Expect 5 more bytes
}
/* We don't test if the UTF-8 encoding is well-formed */
}
return sbuf.toString();
}
}
数据解压缩
http请求的包头带有“Accept-Encoding: gzip,deflate”,则表示客户端支持gzip压缩;那么服务器可能就会返回gzip压缩的应答数据,此时应答包头中会有“Content-Encoding: gzip”。对压缩数据必须先解压后才可正常读取,不然未解压只会读到一堆乱码。输入流的gzip解压使用GZIPInputStream工具类,具体的代码例子如下:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import android.util.Log;
public class StreamTool {
private static final String TAG = "StreamTool";
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return data;
}
public static String getUnzipStream(InputStream is, String content_encoding, String charset) {
String resp_content = "";
GZIPInputStream gzin = null;
if (content_encoding != null && content_encoding.equals("") != true) {
if (content_encoding.indexOf("gzip") >= 0) {
try {
Log.d(TAG, "content_encoding="+content_encoding);
gzin = new GZIPInputStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
if (gzin == null) {
resp_content = new String(readInputStream(is), charset);
} else {
resp_content = new String(readInputStream(gzin), charset);
}
} catch (Exception e) {
e.printStackTrace();
}
return resp_content;
}
}
传递Cookie
携带用户信息访问服务器页面,需要保证会话的有效性,因此http请求的上下文得互相传递Cookie信息。请求数据的Cookie可在请求包头的Cookie字段中传输,应答数据返回的Cookie是在返回包头的Set-Cookie字段。不过应答报文中有时存在多个Set-Cookie字段,遇到这种情况就得分别取出其中Cookie并拼接起来。
HttpURLConnection类获取多个同名包头字段使用getHeaderFields方法,举例如下:
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookies = headerFields.get("Set-Cookie");
HttpClient类获取多个同名包头字段使用getHeaders方法,举例如下:
Header[] cookie_headers = httpResponse.getHeaders("Set-Cookie");
代码示例
下面是HttpURLConnection方式的示例代码:
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.example.exmhttp.util.HttpReqData;
import com.example.exmhttp.util.HttpRespData;
import com.example.exmhttp.util.StreamTool;
import android.graphics.BitmapFactory;
import android.util.Log;
public class HttpUrlUtil {
private static final String TAG = "HttpUrlUtil";
//设置http连接的头部信息
private static void setConnHeader(HttpURLConnection conn, String method, HttpReqData req_data)
throws ProtocolException {
conn.setRequestMethod(method);
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Accept", "*/*");
//IE使用
// conn.setRequestProperty("Accept-Language", "zh-CN");
// conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C)");
//firefox使用
conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
if (req_data.content_type.equals("") != true) {
conn.setRequestProperty("Content-Type", req_data.content_type);
}
if (req_data.x_requested_with.equals("") != true) {
conn.setRequestProperty("X-Requested-With", req_data.x_requested_with);
}
if (req_data.referer.equals("") != true) {
conn.setRequestProperty("Referer", req_data.referer);
}
if (req_data.cookie.equals("") != true) {
conn.setRequestProperty("Cookie", req_data.cookie);
Log.d(TAG, "setConnHeader cookie="+req_data.cookie);
}
}
private static String getRespCookie(HttpURLConnection conn, HttpReqData req_data) {
String cookie = "";
Map<String, List<String>> headerFields = conn.getHeaderFields();
if (headerFields != null) {
List<String> cookies = headerFields.get("Set-Cookie");
if (cookies != null) {
for (String cookie_item : cookies) {
cookie = cookie + cookie_item + "; ";
}
} else {
cookie = req_data.cookie;
}
} else {
cookie = req_data.cookie;
}
Log.d(TAG, "cookie="+cookie);
return cookie;
}
//get文本数据
public static HttpRespData getData(HttpReqData req_data) {
HttpRespData resp_data = new HttpRespData();
try {
URL url = new URL(req_data.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setConnHeader(conn, "GET", req_data);
conn.connect();
resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
conn.getHeaderField("Content-Encoding"), req_data.charset);
resp_data.cookie = conn.getHeaderField("Set-Cookie");
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//get图片数据
public static HttpRespData getImage(HttpReqData req_data) {
HttpRespData resp_data = new HttpRespData();
try {
URL url = new URL(req_data.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setConnHeader(conn, "GET", req_data);
conn.connect();
InputStream is = conn.getInputStream();
resp_data.bitmap = BitmapFactory.decodeStream(is);
resp_data.cookie = conn.getHeaderField("Set-Cookie");
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//post的内容放在url中
public static HttpRespData postUrl(HttpReqData req_data) {
HttpRespData resp_data = new HttpRespData();
String s_url = req_data.url;
if (req_data.params != null) {
s_url += "?" + req_data.params.toString();
}
Log.d(TAG, "s_url="+s_url);
try {
URL url = new URL(s_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setConnHeader(conn, "POST", req_data);
conn.setDoOutput(true);
conn.connect();
resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
conn.getHeaderField("Content-Encoding"), req_data.charset);
resp_data.cookie = conn.getHeaderField("Set-Cookie");
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//post的内容放在输出流中
public static HttpRespData postData(HttpReqData req_data) {
req_data.content_type = "application/x-www-form-urlencoded";
HttpRespData resp_data = new HttpRespData();
String s_url = req_data.url;
Log.d(TAG, "s_url="+s_url+", params="+req_data.params.toString());
try {
URL url = new URL(s_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setConnHeader(conn, "POST", req_data);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(req_data.params.toString());
out.flush();
resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
conn.getHeaderField("Content-Encoding"), req_data.charset);
resp_data.cookie = getRespCookie(conn, req_data);
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//post的内容分段传输
public static HttpRespData postMultiData(HttpReqData req_data, Map<String, String> map) {
HttpRespData resp_data = new HttpRespData();
String s_url = req_data.url;
Log.d(TAG, "s_url="+s_url);
String end = "\r\n";
String hyphens = "--";
try {
URL url = new URL(s_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setConnHeader(conn, "POST", req_data);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+req_data.boundary);
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setDoOutput(true);
conn.setDoInput(true);
StringBuffer buffer = new StringBuffer();
Log.d(TAG, "map.size()=" + map.size());
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String str = it.next();
buffer.append(hyphens + req_data.boundary + end);
buffer.append("Content-Disposition: form-data; name=\"");
buffer.append(str);
buffer.append("\"" + end + end);
buffer.append(map.get(str));
buffer.append(end);
Log.d(TAG, "key=" + str + ", value=" + map.get(str));
}
if (map.size() > 0) {
buffer.append(hyphens + req_data.boundary + end);
byte[] param_data = buffer.toString().getBytes(req_data.charset);
OutputStream out = conn.getOutputStream();
out.write(param_data);
out.flush();
}
conn.connect();
resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
conn.getHeaderField("Content-Encoding"), req_data.charset);
resp_data.cookie = conn.getHeaderField("Set-Cookie");
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
}
下面是HttpClient方式的示例代码:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.example.exmhttp.util.HttpReqData;
import com.example.exmhttp.util.HttpRespData;
import com.example.exmhttp.util.StreamTool;
public class HttpClientUtil {
private static final String TAG = "HttpClientUtil";
private static void setConnHeader(HttpRequestBase conn, HttpReqData req_data) {
conn.setHeader("Accept", "*/*");
//IE使用
// conn.setHeader("Accept-Language", "zh-CN");
// conn.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C)");
//firefox使用
conn.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
conn.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
conn.setHeader("Accept-Encoding", "gzip, deflate");
if (req_data.content_type.equals("") != true) {
conn.setHeader("Content-Type", req_data.content_type);
}
if (req_data.x_requested_with.equals("") != true) {
conn.setHeader("X-Requested-With", req_data.x_requested_with);
}
if (req_data.referer.equals("") != true) {
conn.setHeader("Referer", req_data.referer);
}
if (req_data.cookie.equals("") != true) {
conn.setHeader("Cookie", req_data.cookie);
Log.d(TAG, "setConnHeader cookie="+req_data.cookie);
}
}
private static HttpClient getHttpClient() {
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
return httpClient;
}
private static String getRespContent(HttpEntity httpEntity, HttpResponse httpResponse, String charset) throws Exception {
String content_encoding = "";
Header[] encoding_headers = httpResponse.getHeaders("Content-Encoding");
if (encoding_headers!=null && encoding_headers.length>0) {
content_encoding = encoding_headers[0].getValue();
}
String content = "";
content = StreamTool.getUnzipStream(httpEntity.getContent(), content_encoding, charset);
return content;
}
private static String getRespCookie(HttpResponse httpResponse, HttpReqData req_data) {
String cookie = "";
Header[] cookie_headers = httpResponse.getHeaders("Set-Cookie");
if (cookie_headers != null) {
if (cookie_headers.length == 1) {
cookie = cookie_headers[0].getValue();
} else {
for (int i=0; i<cookie_headers.length; i++) {
Header cookie_header = cookie_headers[i];
cookie = cookie + cookie_header.getValue() + "; ";
}
}
} else {
cookie = req_data.cookie;
}
Log.d(TAG, "cookie="+cookie);
return cookie;
}
//get文本数据
public static HttpRespData getData(HttpReqData req_data) {
HttpRespData resp_data = new HttpRespData();
HttpGet httpGet = new HttpGet(req_data.url);
setConnHeader(httpGet, req_data);
HttpClient httpClient = getHttpClient();
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
resp_data.content = getRespContent(httpEntity, httpResponse, req_data.charset);
resp_data.cookie = getRespCookie(httpResponse, req_data);
Log.d(TAG, "返回内容:"+resp_data.content);
}catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//get图片数据
public static HttpRespData getImage(HttpReqData req_data) {
HttpRespData resp_data = new HttpRespData();
HttpGet httpGet = new HttpGet(req_data.url);
setConnHeader(httpGet, req_data);
HttpClient httpClient = getHttpClient();
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
resp_data.bitmap = BitmapFactory.decodeStream(is);
if (req_data.cookie.equals("") == true) {
resp_data.cookie = getRespCookie(httpResponse, req_data);
}
}catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//post的内容放在url中
public static HttpRespData postUrl(HttpReqData req_data) {
String s_url = req_data.url;
if (req_data.params != null) {
s_url += "?" + req_data.params.toString();
}
Log.d(TAG, "s_url="+s_url);
HttpRespData resp_data = new HttpRespData();
HttpPost httpPost = new HttpPost(s_url);
setConnHeader(httpPost, req_data);
HttpClient httpClient = getHttpClient();
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
resp_data.content = getRespContent(httpEntity, httpResponse, req_data.charset);
resp_data.cookie = getRespCookie(httpResponse, req_data);
Log.d(TAG, "返回内容:"+resp_data.content);
}catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//post的内容放在输出流中
public static HttpRespData postData(HttpReqData req_data) {
HttpRespData resp_data = new HttpRespData();
HttpPost httpPost = new HttpPost(req_data.url);
setConnHeader(httpPost, req_data);
HttpClient httpClient = getHttpClient();
try {
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (req_data.params != null) {
String[] items = req_data.params.toString().split("&");
for (int i=0; i<items.length; i++) {
String item = items[i];
String[] pair = item.split("=");
if (pair.length >= 2) {
list.add(new BasicNameValuePair(pair[0], pair[1]));
}
}
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, req_data.charset);
httpPost.setEntity(entity);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
resp_data.content = getRespContent(httpEntity, httpResponse, req_data.charset);
resp_data.cookie = getRespCookie(httpResponse, req_data);
resp_data.cookie = req_data.cookie + resp_data.cookie;
Log.d(TAG, "返回内容:"+resp_data.content);
}catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
//post的内容分段传输
public static HttpRespData postMultiData(HttpReqData req_data, Map<String, String> map) {
HttpRespData resp_data = new HttpRespData();
HttpPost httpPost = new HttpPost(req_data.url);
setConnHeader(httpPost, req_data);
HttpClient httpClient = getHttpClient();
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setBoundary(req_data.boundary);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
Log.d(TAG, "map.size()=" + map.size());
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String str = it.next();
builder.addPart(str, new StringBody(map.get(str), ContentType.DEFAULT_TEXT));
}
//如果传递图片,则要转为字节流传输
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// bitmap.compress(CompressFormat.JPEG, 75, bos);
// byte[] data = bos.toByteArray();
// ByteArrayBody bab = new ByteArrayBody(data, "this.jpg");
// builder.addPart("image", bab);
// } catch(Exception e){
// builder.addPart("image", new StringBody("image error"));
// }
httpPost.setEntity(builder.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
resp_data.content = getRespContent(httpEntity, httpResponse, req_data.charset);
resp_data.cookie = getRespCookie(httpResponse, req_data);
Log.d(TAG, "返回内容:"+resp_data.content);
}catch (Exception e) {
e.printStackTrace();
resp_data.err_msg = e.getMessage();
}
return resp_data;
}
}
点此查看Android开发笔记的完整目录