1. 程式人生 > >android中模擬http協議表單上傳

android中模擬http協議表單上傳

轉自:http://helloandroid.iteye.com/blog/1183853

利用ie瀏覽器外掛httpwatch檢視form表單上傳時的資料封裝格式,然後照著這資料格式自己一步一步封裝






Java程式碼收藏程式碼
  1. packagecom.android.cist.network.form;
  2. importjava.io.DataOutputStream;
  3. importjava.io.InputStream;
  4. importjava.io.UnsupportedEncodingException;
  5. importjava.net.HttpURLConnection;
  6. import
    java.net.URL;
  7. importjava.net.URLEncoder;
  8. importjava.util.Iterator;
  9. importjava.util.Map;
  10. importjava.util.Set;
  11. publicclassHttpFormUtil{
  12. publicstaticStringpost(StringactionUrl,Map<String,String>params,FormFile[]files){
  13. try{
  14. StringenterNewline="\r\n";
  15. Stringfix="--";
  16. Stringboundary="######"
    ;
  17. StringMULTIPART_FORM_DATA="multipart/form-data";
  18. URLurl=newURL(actionUrl);
  19. HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
  20. con.setDoInput(true);
  21. con.setDoOutput(true);
  22. con.setUseCaches(false);
  23. con.setRequestMethod("POST");
  24. con.setRequestProperty("Connection","Keep-Alive"
    );
  25. con.setRequestProperty("Accept","image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/msword,application/vnd.ms-excel,application/vnd.ms-powerpoint,*/*");
  26. con.setRequestProperty("Accept-Encoding","gzip,deflate");
  27. con.setRequestProperty("Charset","UTF-8");
  28. con.setRequestProperty("Content-Type",MULTIPART_FORM_DATA+";boundary="+boundary);
  29. DataOutputStreamds=newDataOutputStream(con.getOutputStream());
  30. Set<String>keySet=params.keySet();
  31. Iterator<String>it=keySet.iterator();
  32. while(it.hasNext()){
  33. Stringkey=it.next();
  34. Stringvalue=params.get(key);
  35. ds.writeBytes(fix+boundary+enterNewline);
  36. ds.writeBytes("Content-Disposition:form-data;"+"name=\""+key+"\""+enterNewline);
  37. ds.writeBytes(enterNewline);
  38. //ds.write(value.getBytes("UTF-8"));
  39. ds.writeBytes(value);//如果有中文亂碼,儲存改用上面的ds.writeBytes(enterNewline);那句程式碼
  40. ds.writeBytes(enterNewline);
  41. }
  42. if(files!=null&&files.length>0){
  43. ds.writeBytes(fix+boundary+enterNewline);
  44. ds.writeBytes("Content-Disposition:form-data;"+"name=\""+files[0].getFormname()+"\""+";filename=\""+files[0].getFilname()+"\""+enterNewline);
  45. ds.writeBytes(enterNewline);
  46. ds.write(files[0].getData());
  47. ds.writeBytes(enterNewline);
  48. }
  49. ds.writeBytes(fix+boundary+fix+enterNewline);
  50. ds.flush();
  51. InputStreamis=con.getInputStream();
  52. intch;
  53. StringBufferb=newStringBuffer();
  54. while((ch=is.read())!=-1){
  55. b.append((char)ch);
  56. }
  57. ds.close();
  58. returnb.toString().trim();
  59. }catch(Exceptione){
  60. thrownewRuntimeException(e);
  61. }
  62. }
  63. publicstaticStringencode(Stringurl){
  64. try{
  65. returnURLEncoder.encode(url,"UTF-8");
  66. }catch(UnsupportedEncodingExceptionex){
  67. returnurl;
  68. }
  69. }
  70. }