http請求工具

 

  
  
  
  
  1. 代碼  1   
  2.  import java.io.ByteArrayOutputStream;  
  3.  import java.io.DataOutputStream;  
  4.  import java.io.InputStream;  
  5.  import java.net.HttpURLConnection;  
  6.  import java.net.URL;  
  7.  import java.net.URLEncoder;  
  8.  import java.util.Map;  
  9.  import android.util.Log;  
  10.    
  11.  public class NetUtil {  
  12.    
  13.      private static final String TAG = "NetUtil";  
  14.      private static final int RESPONSE_OK = 200;  
  15.        
  16.      public static InputStream sendPostRequest(String urlPath,  
  17.              Map<String, String> params, String encoding) throws Exception {  
  18.          // String param = "method=save&id=24&name="  
  19.          // + URLEncoder.encode("大圓", "UTF-8");  
  20.          StringBuilder sb = new StringBuilder();  
  21.          for (Map.Entry<String, String> entry : params.entrySet()) {  
  22.              sb.append(entry.getKey()).append("=")  
  23.                      .append(URLEncoder.encode(entry.getValue(), encoding))  
  24.                      .append("&");  
  25.          }  
  26.          sb.deleteCharAt(sb.lastIndexOf("&"));  
  27.          byte[] data = sb.toString().getBytes();  
  28.          URL url = new URL(urlPath);  
  29.          HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  30.          conn.setRequestMethod("POST");  
  31.          conn.setReadTimeout(5 * 1000);  
  32.          conn.setDoOutput(true); // 發送POST請求, 必須設置容許輸出  
  33.          conn.setUseCaches(false);  
  34.          conn.setRequestProperty("Connection""Keep-Alive"); // 維持長連接  
  35.          conn.setRequestProperty("Charset""UTF-8");  
  36.          // 設置輸入參數的大小,把參數轉化爲字節數組  
  37.          conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  38.          // 設置數據類型  
  39.          conn.setRequestProperty("Content-Type",  
  40.                  "application/x-www-form-urlencoded");  
  41.            
  42.          DataOutputStream outStream = new DataOutputStream(  
  43.                  conn.getOutputStream());  
  44.          outStream.write(data);  
  45.          outStream.flush();  
  46.          outStream.close();  
  47.          if (conn.getResponseCode() == RESPONSE_OK) {  
  48.              return conn.getInputStream();  
  49.          }  
  50.          return null;  
  51.      }  
  52.    
  53.      /*  
  54.       * 獲得http返回的輸入流,而且轉化成String  
  55.       */ 
  56.      public static String getTextContent(String urlPath, String encoding)  
  57.              throws Exception {  
  58.          URL url = new URL(urlPath);  
  59.          HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  60.          conn.setRequestMethod("GET");  
  61.          conn.setReadTimeout(5 * 1000);  
  62.          if (conn.getResponseCode() == RESPONSE_OK) {  
  63.              InputStream inStream = conn.getInputStream();  
  64.              byte[] data = readStream(inStream);  
  65.              System.out.println(new String(data, encoding));  
  66.              return new String(data, encoding);  
  67.          }  
  68.          return null;  
  69.      }  
  70.    
  71.      // 讀取數據  
  72.      public static byte[] readStream(InputStream inStream) throws Exception {  
  73.          ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  74.          byte[] buffer = new byte[2048];  
  75.          int length = -1;  
  76.          while ((length = (inStream.read(buffer))) != -1) {  
  77.              outStream.write(buffer, 0, length);  
  78.          }  
  79.          outStream.close();  
  80.          return outStream.toByteArray();  
  81.      }  
  82.    
  83.      // 直接返回http獲得的輸入流  
  84.      public static InputStream getStreamContent(String urlPath, String encoding)  
  85.              throws Exception {  
  86.          InputStream inStream = null;  
  87.          URL url = new URL(urlPath);  
  88.          HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  89.          conn.setRequestMethod("GET");  
  90.          conn.setReadTimeout(5 * 1000);  
  91.          if (conn.getResponseCode() == RESPONSE_OK) {  
  92.              inStream = conn.getInputStream();  
  93.          }  
  94.          return inStream;  
  95.      }  
  96.    
  97.      public static void print(String tag, String msg) {  
  98.          Log.d(tag, msg);  
  99.      }  
  100.  } 

 

  
  
  
  
  1. 代碼 1 public class FormFile {  
  2.      // 上傳文件的數據  
  3.      private byte[] data;  
  4.    
  5.      private InputStream inStream;  
  6.    
  7.      // 文件名稱  
  8.      private String filename;  
  9.      // 表單名稱  
  10.      private String formname;  
  11.      // 內容類型  
  12.      private String contentType = "application/octet-stream";  
  13.    
  14.      public FormFile(String filename, byte[] data, String formname,  
  15.              String contentType) {  
  16.          this.data = data;  
  17.          this.filename = filename;  
  18.          this.formname = formname;  
  19.          if (contentType != null) {  
  20.              this.contentType = contentType;  
  21.          }  
  22.      }  
  23.    
  24.      public FormFile(String filename, InputStream inStream, String formname,  
  25.              String contentType) {  
  26.          this.filename = filename;  
  27.          this.formname = formname;  
  28.          this.inStream = inStream;  
  29.          if (contentType != null) {  
  30.              this.contentType = contentType;  
  31.          }  
  32.      }  
  33.    
  34.      public byte[] getData() {  
  35.          return data;  
  36.      }  
  37.    
  38.      public void setData(byte[] data) {  
  39.          this.data = data;  
  40.      }  
  41.    
  42.      public InputStream getInStream() {  
  43.          return inStream;  
  44.      }  
  45.    
  46.      public void setInStream(InputStream inStream) {  
  47.          this.inStream = inStream;  
  48.      }  
  49.    
  50.      public String getFilename() {  
  51.          return filename;  
  52.      }  
  53.    
  54.      public void setFilename(String filename) {  
  55.          this.filename = filename;  
  56.      }  
  57.    
  58.      public String getFormname() {  
  59.          return formname;  
  60.      }  
  61.    
  62.      public void setFormname(String formname) {  
  63.          this.formname = formname;  
  64.      }  
  65.    
  66.      public String getContentType() {  
  67.          return contentType;  
  68.      }  
  69.    
  70.      public void setContentType(String contentType) {  
  71.          this.contentType = contentType;  
  72.      }  
  73.  }  
  74.  代碼  1 public class HttpUploadRequester {  
  75.      /**  
  76.       * 直接經過HTTP協議提交數據到服務器,實現以下面表單提交功能: <FORM METHOD=POST  
  77.       * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"  
  78.       * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT  
  79.       * TYPE="text" NAME="id"> <input type="file" name="p_w_picpathfile"/> <input  
  80.       * type="file" name="zip"/> </FORM>  
  81.       *   
  82.       * @param actionUrl  
  83.       *            上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,由於它會指向手機模擬器,  
  84.       *            你能夠使用http://192.168.1.10:8080這樣的路徑測試)  
  85.       * @param params  
  86.       *            請求參數 key爲參數名,value爲參數值  
  87.       * @param file  
  88.       *            上傳文件  
  89.       */ 
  90.      // http協議中分割符,隨便定義  
  91.      private static final String HTTP_BOUNDARY = "---------9dx5a2d578c2";  
  92.      private static final String MULTIPART_FORM_DATA = "multipart/form-data";  
  93.      private static final String LINE_ENTER = "\r\n"// 換行 回車  
  94.      private static final int RESPONSE_OK = 200;  
  95.    
  96.      public static String post(String urlPath, Map<String, String> params,  
  97.              FormFile[] formFiles) {  
  98.          try {  
  99.              URL url = new URL(urlPath);  
  100.              HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  101.              conn.setRequestMethod("POST");  
  102.              conn.setReadTimeout(5 * 1000);  
  103.              conn.setDoOutput(true); // 發送POST請求, 必須設置容許輸出  
  104.              conn.setUseCaches(false);  
  105.              conn.setRequestProperty("Connection""Keep-Alive"); // 維持長連接  
  106.              conn.setRequestProperty("Charset""UTF-8");  
  107.              conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA  
  108.                      + "; boundary=" + HTTP_BOUNDARY);  
  109.    
  110.              StringBuilder formItemData = new StringBuilder();  
  111.              // 構建 表單字段內容  
  112.              for (Map.Entry<String, String> entry : params.entrySet()) {  
  113.                  formItemData.append("--");  
  114.                  formItemData.append(HTTP_BOUNDARY);  
  115.                  formItemData.append(LINE_ENTER);  
  116.                  formItemData.append("Content-Disposition: form-data; name=\"" 
  117.                          + entry.getKey() + "\"\r\n\r\n");  
  118.                  formItemData.append(entry.getValue());  
  119.                  formItemData.append(LINE_ENTER);  
  120.              }  
  121.              DataOutputStream outStream = new DataOutputStream(  
  122.                      conn.getOutputStream());  
  123.              // 發送表單字段內容到服務器  
  124.              outStream.write(formItemData.toString().getBytes());  
  125.    
  126.              // 發送上傳文件數據  
  127.              for (FormFile fileData : formFiles) {  
  128.                  StringBuilder fileSplit = new StringBuilder();  
  129.                  fileSplit.append("--");  
  130.                  fileSplit.append(HTTP_BOUNDARY);  
  131.                  fileSplit.append(LINE_ENTER);  
  132.                  fileSplit.append("Content-Disposition: form-data;name=\"" 
  133.                          + fileData.getFormname() + "\";filename=\"" 
  134.                          + fileData.getFilename() + "\"\r\n");  
  135.                  fileSplit.append("Content-Type:" + fileData.getContentType()  
  136.                          + LINE_ENTER + LINE_ENTER);  
  137.                  outStream.write(fileSplit.toString().getBytes());  
  138.    
  139.                  if (fileData.getInStream() != null) {  
  140.                      byte[] buffer = new byte[1024];  
  141.                      int length = 0;  
  142.                      while ((length = fileData.getInStream().read()) != -1) {  
  143.                          outStream.write(buffer, 0, length);  
  144.                      }  
  145.                      fileData.getInStream().close();  
  146.                  } else {  
  147.                      outStream.write(fileData.getData(), 0,  
  148.                              fileData.getData().length);  
  149.                  }  
  150.                  outStream.write(LINE_ENTER.getBytes());  
  151.              }  
  152.              // 數據結束標誌  
  153.              byte[] endData = ("--" + HTTP_BOUNDARY + "--" + LINE_ENTER)  
  154.                      .getBytes();  
  155.              outStream.write(endData);  
  156.              outStream.flush();  
  157.              outStream.close();  
  158.              int responseCode = conn.getResponseCode();  
  159.              if (responseCode != RESPONSE_OK) {  
  160.                  throw new RuntimeException("請求url失敗");  
  161.              }  
  162.              InputStream is = conn.getInputStream();  
  163.              int ch;  
  164.              StringBuilder b = new StringBuilder();  
  165.              while ((ch = is.read()) != -1) {  
  166.                  b.append((char) ch);  
  167.              }  
  168.              Log.i("HttpPost", b.toString());  
  169.              conn.disconnect();  
  170.              return b.toString();  
  171.          } catch (Exception e) {  
  172.              throw new RuntimeException();  
  173.          }  
  174.      }  
  175.    
  176.      // 上傳單個文件  
  177.      public static String post(String urlPath, Map<String, String> params,  
  178.              FormFile formFiles) {  
  179.          return post(urlPath, params, new FormFile[] { formFiles });  
  180.      }  
  181.  }  
  182.  代碼 1   // 以表單方式發送請求  
  183.    
  184.           public static void sendDataToServerByForm() throws Exception {  
  185.    
  186.                     Map<String, String> params = new HashMap<String, String>();  
  187.    
  188.                     params.put("method""sendDataByForm");  
  189.    
  190.                     params.put("strData""字符串數據");  
  191.    
  192.                     // 獲取SDCard中的good.jpg  
  193.    
  194.                     File file = new File(Environment.getExternalStorageDirectory(),  
  195.    
  196.                                       "app_Goog_Android_w.png");  
  197.    
  198.                     FormFile fileData = new FormFile("app_Goog_Android_w.png"new FileInputStream(file),  
  199.    
  200.                                       "fileData""application/octet-stream");  
  201.    
  202.                     HttpUploadRequester.post(  
  203.    
  204.                                       "http://192.168.0.2:8080/AndroidWebServer/server.do", params,  
  205.    
  206.                                       fileData);  
  207.    
  208.           } 
相關文章
相關標籤/搜索