- 代碼 1
- import java.io.ByteArrayOutputStream;
- import java.io.DataOutputStream;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.Map;
- import android.util.Log;
- public class NetUtil {
- private static final String TAG = "NetUtil";
- private static final int RESPONSE_OK = 200;
- public static InputStream sendPostRequest(String urlPath,
- Map<String, String> params, String encoding) throws Exception {
- // String param = "method=save&id=24&name="
- // + URLEncoder.encode("大圓", "UTF-8");
- StringBuilder sb = new StringBuilder();
- for (Map.Entry<String, String> entry : params.entrySet()) {
- sb.append(entry.getKey()).append("=")
- .append(URLEncoder.encode(entry.getValue(), encoding))
- .append("&");
- }
- sb.deleteCharAt(sb.lastIndexOf("&"));
- byte[] data = sb.toString().getBytes();
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setReadTimeout(5 * 1000);
- conn.setDoOutput(true); // 發送POST請求, 必須設置容許輸出
- conn.setUseCaches(false);
- conn.setRequestProperty("Connection", "Keep-Alive"); // 維持長連接
- conn.setRequestProperty("Charset", "UTF-8");
- // 設置輸入參數的大小,把參數轉化爲字節數組
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- // 設置數據類型
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- DataOutputStream outStream = new DataOutputStream(
- conn.getOutputStream());
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if (conn.getResponseCode() == RESPONSE_OK) {
- return conn.getInputStream();
- }
- return null;
- }
- /*
- * 獲得http返回的輸入流,而且轉化成String
- */
- public static String getTextContent(String urlPath, String encoding)
- throws Exception {
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setReadTimeout(5 * 1000);
- if (conn.getResponseCode() == RESPONSE_OK) {
- InputStream inStream = conn.getInputStream();
- byte[] data = readStream(inStream);
- System.out.println(new String(data, encoding));
- return new String(data, encoding);
- }
- return null;
- }
- // 讀取數據
- public static byte[] readStream(InputStream inStream) throws Exception {
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[2048];
- int length = -1;
- while ((length = (inStream.read(buffer))) != -1) {
- outStream.write(buffer, 0, length);
- }
- outStream.close();
- return outStream.toByteArray();
- }
- // 直接返回http獲得的輸入流
- public static InputStream getStreamContent(String urlPath, String encoding)
- throws Exception {
- InputStream inStream = null;
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setReadTimeout(5 * 1000);
- if (conn.getResponseCode() == RESPONSE_OK) {
- inStream = conn.getInputStream();
- }
- return inStream;
- }
- public static void print(String tag, String msg) {
- Log.d(tag, msg);
- }
- }
- 代碼 1 public class FormFile {
- // 上傳文件的數據
- private byte[] data;
- private InputStream inStream;
- // 文件名稱
- private String filename;
- // 表單名稱
- private String formname;
- // 內容類型
- private String contentType = "application/octet-stream";
- public FormFile(String filename, byte[] data, String formname,
- String contentType) {
- this.data = data;
- this.filename = filename;
- this.formname = formname;
- if (contentType != null) {
- this.contentType = contentType;
- }
- }
- public FormFile(String filename, InputStream inStream, String formname,
- String contentType) {
- this.filename = filename;
- this.formname = formname;
- this.inStream = inStream;
- if (contentType != null) {
- this.contentType = contentType;
- }
- }
- public byte[] getData() {
- return data;
- }
- public void setData(byte[] data) {
- this.data = data;
- }
- public InputStream getInStream() {
- return inStream;
- }
- public void setInStream(InputStream inStream) {
- this.inStream = inStream;
- }
- public String getFilename() {
- return filename;
- }
- public void setFilename(String filename) {
- this.filename = filename;
- }
- public String getFormname() {
- return formname;
- }
- public void setFormname(String formname) {
- this.formname = formname;
- }
- public String getContentType() {
- return contentType;
- }
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
- }
- 代碼 1 public class HttpUploadRequester {
- /**
- * 直接經過HTTP協議提交數據到服務器,實現以下面表單提交功能: <FORM METHOD=POST
- * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"
- * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT
- * TYPE="text" NAME="id"> <input type="file" name="p_w_picpathfile"/> <input
- * type="file" name="zip"/> </FORM>
- *
- * @param actionUrl
- * 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,由於它會指向手機模擬器,
- * 你能夠使用http://192.168.1.10:8080這樣的路徑測試)
- * @param params
- * 請求參數 key爲參數名,value爲參數值
- * @param file
- * 上傳文件
- */
- // http協議中分割符,隨便定義
- private static final String HTTP_BOUNDARY = "---------9dx5a2d578c2";
- private static final String MULTIPART_FORM_DATA = "multipart/form-data";
- private static final String LINE_ENTER = "\r\n"; // 換行 回車
- private static final int RESPONSE_OK = 200;
- public static String post(String urlPath, Map<String, String> params,
- FormFile[] formFiles) {
- try {
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setReadTimeout(5 * 1000);
- conn.setDoOutput(true); // 發送POST請求, 必須設置容許輸出
- conn.setUseCaches(false);
- conn.setRequestProperty("Connection", "Keep-Alive"); // 維持長連接
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
- + "; boundary=" + HTTP_BOUNDARY);
- StringBuilder formItemData = new StringBuilder();
- // 構建 表單字段內容
- for (Map.Entry<String, String> entry : params.entrySet()) {
- formItemData.append("--");
- formItemData.append(HTTP_BOUNDARY);
- formItemData.append(LINE_ENTER);
- formItemData.append("Content-Disposition: form-data; name=\""
- + entry.getKey() + "\"\r\n\r\n");
- formItemData.append(entry.getValue());
- formItemData.append(LINE_ENTER);
- }
- DataOutputStream outStream = new DataOutputStream(
- conn.getOutputStream());
- // 發送表單字段內容到服務器
- outStream.write(formItemData.toString().getBytes());
- // 發送上傳文件數據
- for (FormFile fileData : formFiles) {
- StringBuilder fileSplit = new StringBuilder();
- fileSplit.append("--");
- fileSplit.append(HTTP_BOUNDARY);
- fileSplit.append(LINE_ENTER);
- fileSplit.append("Content-Disposition: form-data;name=\""
- + fileData.getFormname() + "\";filename=\""
- + fileData.getFilename() + "\"\r\n");
- fileSplit.append("Content-Type:" + fileData.getContentType()
- + LINE_ENTER + LINE_ENTER);
- outStream.write(fileSplit.toString().getBytes());
- if (fileData.getInStream() != null) {
- byte[] buffer = new byte[1024];
- int length = 0;
- while ((length = fileData.getInStream().read()) != -1) {
- outStream.write(buffer, 0, length);
- }
- fileData.getInStream().close();
- } else {
- outStream.write(fileData.getData(), 0,
- fileData.getData().length);
- }
- outStream.write(LINE_ENTER.getBytes());
- }
- // 數據結束標誌
- byte[] endData = ("--" + HTTP_BOUNDARY + "--" + LINE_ENTER)
- .getBytes();
- outStream.write(endData);
- outStream.flush();
- outStream.close();
- int responseCode = conn.getResponseCode();
- if (responseCode != RESPONSE_OK) {
- throw new RuntimeException("請求url失敗");
- }
- InputStream is = conn.getInputStream();
- int ch;
- StringBuilder b = new StringBuilder();
- while ((ch = is.read()) != -1) {
- b.append((char) ch);
- }
- Log.i("HttpPost", b.toString());
- conn.disconnect();
- return b.toString();
- } catch (Exception e) {
- throw new RuntimeException();
- }
- }
- // 上傳單個文件
- public static String post(String urlPath, Map<String, String> params,
- FormFile formFiles) {
- return post(urlPath, params, new FormFile[] { formFiles });
- }
- }
- 代碼 1 // 以表單方式發送請求
- public static void sendDataToServerByForm() throws Exception {
- Map<String, String> params = new HashMap<String, String>();
- params.put("method", "sendDataByForm");
- params.put("strData", "字符串數據");
- // 獲取SDCard中的good.jpg
- File file = new File(Environment.getExternalStorageDirectory(),
- "app_Goog_Android_w.png");
- FormFile fileData = new FormFile("app_Goog_Android_w.png", new FileInputStream(file),
- "fileData", "application/octet-stream");
- HttpUploadRequester.post(
- "http://192.168.0.2:8080/AndroidWebServer/server.do", params,
- fileData);
- }