標籤:android des style http java 使用
這是主函數package com.zmb.updemo;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.UUID;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.app.Activity;import android.app.AlertDialog;import android.content.ContentResolver;import android.content.Intent;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.provider.MediaStore;import android.util.Log;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener{ private Button mBtnUpload,whether; private ProgressBar mPgBar; private TextView mTvProgress; private Button choose; private ImageView imageView; private File file; private UpLoadTask upLoadTask; private static final int TIME_OUT = 120*10000000; //逾時時間 private static final String CHARSET = "utf-8"; //設定編碼 private static final String RequestURL="http://192.168.0.164:9580/ekp/TestServlet"; private AlertDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnUpload = (Button)findViewById(R.id.uploadImage); choose = (Button)findViewById(R.id.selectImage); imageView=(ImageView) findViewById(R.id.imageView); mBtnUpload.setOnClickListener(this); choose.setOnClickListener(this); View upView = getLayoutInflater().inflate(R.layout.progress_bar_item, null); mPgBar = (ProgressBar)upView.findViewById(R.id.pb_filebrowser_uploading); mTvProgress = (TextView)upView.findViewById(R.id.tv_filebrowser_uploading); whether = (Button)upView.findViewById(R.id.upload_over); whether.setOnClickListener(this); dialog=new AlertDialog.Builder(MainActivity.this).setView(upView).create(); } private class UpLoadTask extends AsyncTask<Void, Integer, String>{ @Override protected void onPostExecute(String result) { mTvProgress.setText(result); whether.setText("確定"); } @Override protected void onPreExecute() { dialog.show(); mTvProgress.setText("正在上傳圖片..."); whether.setText("取消"); } @Override protected void onProgressUpdate(Integer... values) { Integer num=values[0]; mPgBar.setProgress(num); mTvProgress.setText("正在上傳圖片..." + num + "%"); } @Override protected String doInBackground(Void...parem) { String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機產生 String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //內容類型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); //允許輸入資料流 conn.setDoOutput(true); //允許輸出資料流 conn.setUseCaches(false); //不允許使用緩衝 conn.setRequestMethod("POST"); //請求方式 conn.setRequestProperty("Charset", CHARSET); //設定編碼 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if(file!=null) { /** * 當檔案不為空白,把檔案封裝並且上傳 */ OutputStream outputSteam=conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 這裡重點注意: * name裡面的值為伺服器端需要key 只有這個key 才可以得到對應的檔案 * filename是檔案的名字,包含尾碼名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream fis = new FileInputStream(file); long total = fis.available(); String totalstr = String.valueOf(total); Log.d("檔案大小", totalstr); byte[] buffer = new byte[8192]; // 8k int count = 0; int length = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); length += count; publishProgress((int) ((length / (float) total) * 100)); //為了示範進度,休眠50毫秒 Thread.sleep(50); } fis.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 擷取響應碼 200=成功 * 當響應成功,擷取響應的流 */ int res = conn.getResponseCode(); if(res==200) { return "上傳成功!"; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return "上傳失敗!"; }} @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { int id=v.getId(); switch (id) { case R.id.selectImage: /*** * 這個是調用android內建的intent,來過濾圖片檔案 ,同時也可以過濾其他的 */ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); //回調圖片類使用的 startActivityForResult(intent, RESULT_CANCELED); break; case R.id.upload_over: if("確定".equals(whether.getText()+"")){ dialog.dismiss(); }else{ upLoadTask.cancel(true); dialog.dismiss(); } break; default: /* //這裡的view是上傳進度的彈框 //AsyncTask的執行個體 upLoadTask=new UpLoadTask(); upLoadTask.execute();*/ HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("http://192.168.0.164:9580/ekp/TestServlet"); try { HttpResponse response = client.execute(get); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); for (String s = reader.readLine(); s != null; s = reader.readLine()) { System.out.println("------------------??????"); } } catch (Exception e) { e.printStackTrace(); } break; } } /** * 回調執行的方法 */ @SuppressWarnings("deprecation") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==Activity.RESULT_OK) { /** * 當選擇的圖片不為空白的話,在擷取到圖片的途徑 */ Uri uri = data.getData(); try { String[] pojo = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri, pojo, null, null,null); if(cursor!=null) { ContentResolver cr = this.getContentResolver(); int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); /*** * 這裡加這樣一個判斷主要是為了第三方的軟體選擇,比如:使用第三方的檔案管理工具的話,你選擇的檔案就不一定是圖片了,這樣的話,我們判斷檔案的尾碼名 * 如果是圖片格式的話,那麼才可以 */ if(path.endsWith("jpg")||path.endsWith("png")) { file=new File(path); Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); imageView.setImageBitmap(bitmap); } } } catch (Exception e) { e.printStackTrace(); } } /** * 回調使用 */ super.onActivityResult(requestCode, resultCode, data); } }
主設定檔
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="選擇圖片" android:id="@+id/selectImage" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="上傳圖片" android:id="@+id/uploadImage" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" /></LinearLayout>
還有一個進度條的設定檔
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" > <ProgressBar android:id="@+id/pb_filebrowser_uploading" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/tv_filebrowser_uploading" android:layout_width="match_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/upload_over" android:layout_width="match_parent" android:layout_height="wrap_content"/></LinearLayout>