import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.leopard.health.model.Constants;
import com.leopard.health.model.response.BaseResponse;
import com.leopard.health.service.Impl.UserServiceImpl;
/**
*
* Http工具
*
* @author wyyl1
*
* @date 2012-9-13
*/
public class HttpUtil {
private static final String CODING_UTF_8 = "UTF-8";
public static BaseResponse sendPost(String url)
throws ClientProtocolException, IOException, JSONException {
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(url);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getEntity() != null) {
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
BaseResponse respones = new BaseResponse(strResult);
respones.setHttpCode(httpResponse.getStatusLine().getStatusCode());
return respones;
} else {
return null;
}
}
public static BaseResponse sendPost(String url, List<NameValuePair> params)
throws ClientProtocolException, IOException, JSONException {
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(url);
// 添加要传递的参数
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, CODING_UTF_8);
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getEntity() != null) {
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
Log.d("StatusCode", ""
+ httpResponse.getStatusLine().getStatusCode());
Log.d("返回的字符串", strResult);
BaseResponse respones = new BaseResponse(strResult);
respones.setHttpCode(httpResponse.getStatusLine().getStatusCode());
return respones;
} else {
return null;
}
}
public static BaseResponse sendPost(String url, HttpParams params,
File file, String contentType) throws ClientProtocolException,
IOException, JSONException {
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(url);
// 添加要传递的参数
// // 设置字符集
List<NameValuePair> paramshttpentity = new ArrayList<NameValuePair>();
paramshttpentity.add(new BasicNameValuePair(Constants.SYN_SID,
UserServiceImpl.loginedUser.getSessionId()));
paramshttpentity
.add(new BasicNameValuePair("app_id", Constants.APP_ID));
// HttpEntity httpentity = new UrlEncodedFormEntity(paramshttpentity,
// CODING_UTF_8);
// // 请求httpRequest
// httpRequest.setEntity(httpentity);
FileEntity fe = new FileEntity(file, contentType);
httpRequest.setEntity(fe);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse"
HttpResponse httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getEntity() != null) {
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
Log.d("StatusCode", ""
+ httpResponse.getStatusLine().getStatusCode());
Log.d("返回的字符串", strResult);
BaseResponse respones = new BaseResponse(strResult);
respones.setHttpCode(httpResponse.getStatusLine().getStatusCode());
return respones;
} else {
return null;
}
}
/**
* 上传文件
* @param actionUrl 上传地址
* @param name 服务器接收文件的字段名
* @param uploadFile 文件地址
* @param newName 在服务器上希望保存的名字
* @return
*/
public static String uploadFile(String actionUrl, String name, String uploadFile,
String newName) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
DataOutputStream ds = null;
StringBuffer b = new StringBuffer();
try {
URL url = new URL(actionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设定传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
/* 设定DataOutputStream */
ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"img\";filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(uploadFile);
/* 设定每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据到缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
/* 将数据写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
Log.d("res", b.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭DataOutputStream
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return b.toString();
}
/**
* 下载图片
* @param url
* @return
*/
public static Bitmap downloadImage(String url) {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpGet request = new HttpGet(url);
Log.d("downloadImgurl", "[][][][][][][]=" + url);
HttpResponse response = httpClient.execute(request);
byte[] image = EntityUtils.toByteArray(response.getEntity());
Bitmap mBitmap = BitmapFactory.decodeByteArray(image, 0,
image.length);
return mBitmap;
} catch (IOException e) {
// covers:
// ClientProtocolException
// ConnectTimeoutException
// ConnectionPoolTimeoutException
// SocketTimeoutException
e.printStackTrace();
}
return null;
}
}
参考资料:
上传文件方法:《Google Android SDK开发范例大全》
下载图片方法:《精通Android3》