1. 程式人生 > >HttpURLConnection form-data的post方式,提交圖片資訊

HttpURLConnection form-data的post方式,提交圖片資訊

package wuxi.mantoo.intelligentbag.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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.json.JSONException;
import org.json.JSONObject;

import wuxi.mantoo.intelligentbag.config.ManUrl;
import android.util.Log;

public class UpLoadPickture {

	private final String TAG = "UpLoadPickture";

	/* sumber server */
	public void uploadPickture(final String piktrueRoute) {

		/*
		 * visit server
		 */
		// next line
		final String newLine = "\r\n";
		final String boundaryPrefix = "--";
		// data division
		final String BOUNDARY = UUID.randomUUID().toString();

		new Thread() {

			public void run() {
				String target = ManUrl.UPLOAD; // 要提交的目標地址
				URL url;
				try {
					url = new URL(target);
					HttpURLConnection urlConn = (HttpURLConnection) url
							.openConnection(); // 建立一個HTTP連線
					urlConn.setRequestMethod("POST"); // 指定使用POST請求方式
					urlConn.setDoInput(true); // 向連線中寫入資料
					urlConn.setDoOutput(true); // 從連線中讀取資料
					urlConn.setUseCaches(false); // 禁止快取
					urlConn.setInstanceFollowRedirects(true); // 自動執行HTTP重定向
					urlConn.setRequestProperty("connection", "Keep-Alive");
					urlConn.setRequestProperty("Charset", "UTF-8");
					urlConn.setRequestProperty("Content-Type",
							"multipart/form-data; boundary=" + BOUNDARY); // 設定內容型別
					DataOutputStream out = new DataOutputStream(
							urlConn.getOutputStream()); // 獲取輸出流

					// 上傳檔案
					File file = new File(piktrueRoute);
					StringBuilder sb = new StringBuilder();
					sb.append(boundaryPrefix);
					sb.append(BOUNDARY);
					sb.append(newLine);

					/**
					 *檔案引數,photo引數名可以隨意修改
					 *photo 為伺服器的key
					 *如果伺服器設定了這個key就要改成響應的引數
					*/
					sb.append("Content-Disposition: form-data;name=\"photo\";filename=\""
							+ file.getName() + "\"" + newLine);
					sb.append("Content-Type:application/octet-stream");
					// 引數頭設定完以後需要兩個換行,然後才是引數內容
					sb.append(newLine);
					sb.append(newLine);
					// 將引數頭的資料寫入到輸出流中
					out.write(sb.toString().getBytes());
					// 資料輸入流,用於讀取檔案資料
					DataInputStream in = new DataInputStream(
							new FileInputStream(file));
					byte[] bufferOut = new byte[1024];
					int bytes = 0;
					// 每次讀1KB資料,並且將檔案資料寫入到輸出流中
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					// 最後新增換行
					out.write(newLine.getBytes());
					in.close();

					// 定義最後資料分隔線,即--加上BOUNDARY再加上--。
					byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
							+ boundaryPrefix + newLine).getBytes();
					// 寫上結尾標識
					out.write(end_data);
					out.flush(); // 輸出快取
					out.close(); // 關閉資料輸出流
					Log.i(TAG, "getResponseCode:" + urlConn.getResponseCode());
					if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 判斷是否響應成功
						InputStreamReader in1 = new InputStreamReader(
								urlConn.getInputStream(), "utf-8"); // 獲得讀取的內容,utf-8獲取內容的編碼
						BufferedReader buffer = new BufferedReader(in1); // 獲取輸入流物件
						String inputLine = null;
						Log.d(TAG, "inputLine:" + buffer.readLine());
						while ((inputLine = buffer.readLine()) != null) {
							Log.d(TAG, inputLine + "\n");
							try {
								JSONObject reader = new JSONObject(inputLine);// 使用JSONObject解析
								JSONObject reObjectData = reader
										.getJSONObject("data");

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								Log.i(TAG, e.getMessage());
							}
						}

						in1.close(); // 關閉字元輸入流
					}
					urlConn.disconnect(); // 斷開連線
				} catch (MalformedURLException e) {
					e.printStackTrace();
					Log.i(TAG, e.getMessage());
				} catch (IOException e) {
					e.printStackTrace();
					Log.i(TAG, e.getMessage());
				}
			};
		}.start();

	}

}