android的http工具類

來源:互聯網
上載者:User
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);// 取得預設的HttpClientHttpClient httpclient = new DefaultHttpClient();// 取得HttpResponseHttpResponse 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);// 請求httpRequesthttpRequest.setEntity(httpentity);// 取得預設的HttpClientHttpClient httpclient = new DefaultHttpClient();// 取得HttpResponseHttpResponse 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);// 取得預設的HttpClientHttpClient 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 {// 關閉DataOutputStreamds.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// SocketTimeoutExceptione.printStackTrace();}return null;}}

參考資料:

上傳檔案方法:《Google Android SDK開發範例大全》

下載圖片方法:《精通Android3》

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.