httpmime-4.1.3 簡單使用
阿新 • • 發佈:2019-01-07
轉載自:http://blog.csdn.net/eddysong9280/article/details/9923391
HttpClient 是 Apache Jakarta Common 下的子專案,可以用來提供高效的、最新的、功能豐富的支援 HTTP 協議的客戶端程式設計工具包,並且它支援 HTTP 協議最新的版本和建議(CV大法來自於HttpClient百度百科,- -),httpclient的jar包可去apache官網或者csdn或者iask下載(個人感覺iask還是不錯的,至少好多資源免積分,而且裡面還有很多意想不到的資源哦, - -)。
言歸正傳,介紹專案中使用的httpmime-4.1.3.jar包使用,理解jar包裡面的類定義及屬性方法可參照其javadoc,下面直接上程式碼。
- publicclass HttpworkTask extends Thread {
- publicfinalstatic String TAG = "HttpworkTask"; //log tag
- private NetworkListener listener;
- privatestatic HttpClient httpClient;
- privatefinalstaticint CONNECTIONTIMEOUT = 10000;//http連結超時
-
privatefinalstaticint REQUESTTIMEOUT = 20000;//http資料請求超時
- private String url = null;
- private Map<String, Object> paras = null;//post的StringBody
- private Map<String, File> fileParas = null;//post的FileBody
- public HttpworkTask(String url, Map<String, Object> paras, Map<String, File> fileParas){
-
this.url = url;
- this.paras = paras;
- this.fileParas = fileParas;
- }
- @Override
- publicvoid run() {
- BufferedReader br = null;
- StringBuilder sBuilder = new StringBuilder();
- HttpParams httpParams = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTIONTIMEOUT);
- HttpConnectionParams.setSoTimeout(httpParams, REQUESTTIMEOUT);
- SchemeRegistry registry = new SchemeRegistry();
- registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
- //由於是使用執行緒操作http,所以設定Thread safe屬性,不然當start多個httpworktask執行緒時必然報錯,這點需要注意
- httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); HttpPost post = new HttpPost(url);
- //新增 post的String 和File資料
- MultipartEntity entity = new MultipartEntity();
- try {
- // 新增引數
- if (paras != null && !paras.isEmpty()) {
- for (Map.Entry<String, Object> item : paras.entrySet()) {
- entity.addPart(item.getKey(), new StringBody(item.getValue().toString(), Charset.forName("UTF-8")));
- }
- }
- // 新增檔案
- if (fileParas != null && !fileParas.isEmpty()) {
- for (Map.Entry<String, File> item : fileParas.entrySet()) {
- if (item.getValue().exists()) {
- Log.i(TAG, "upload File is exists and filepath is-->" + item.getKey() + " " + item.getValue().getPath());
- entity.addPart(item.getKey(), new FileBody(item.getValue()));
- }else{
- Log.e(TAG, "upload File is NOT exists!");
- }
- }
- }
- post.setEntity(entity);
- HttpResponse response = httpClient.execute(post);
- int statecode = response.getStatusLine().getStatusCode();
- Log.i(TAG, "http response code-->" + statecode);
- if (statecode == HttpStatus.SC_OK) {
- HttpEntity responseEntity = response.getEntity();
- if (responseEntity != null) {
- InputStream is = responseEntity.getContent();
- br = new BufferedReader(new InputStreamReader(is));
- String tempStr;
- while ((tempStr = br.readLine()) != null) {
- sBuilder.append(tempStr);
- }
- br.close();
- }
- }
- } catch (Exception e) {
- listener.onConnectionError(NetworkListener.NET_ERROR, "http connect is error,pls check your phone network");
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- post.abort();
- //http返回的資料
- String resData = sBuilder.toString();
- Log.i(TAG, "http server response -->" + resData);
- if (resData != null) {
- listener.onConnectionRecieveData(resData.getBytes(), resData.length());
- }
- }
- publicstaticvoid shutdownHttp() {
- if (httpClient != null) {
- httpClient.getConnectionManager().shutdown();
- }
- }
- }
- 說明幾點:1.使用MultipartEntity,Stringbody和FileBody可同時post。
- 2.可同時上傳n個File檔案。
- 一般在定義http業務的json協議時,如json上傳照片檔案,imgUrls:圖片檔案(同時上傳多張圖片),entity.addPart的第一個引數為fileParas map的key值應為imgUrls,這樣多次addpart後會不會頂掉前面add的filebody呢(key值相同啊)?其實不會!具體可看下addpart函式的實現原始碼,它是用addpart的兩個引數生成一個物件放到一個list中去了。