http 上传文件的方法


  1. /**
  2.          *
  3.          * sendMultipartDataToHttpServer
  4.          * 使用post方法请求web服务器,并且当表单数据为:multipart/form-data格式。 http请求使用{@link#HTTP_ENCODING}编码<br/>
  5.          * 返回json数据,支持文件名中文上传和多文件上传,不支持断点上传,要正确编码服务 端返回{@link#HTTP_ENCODING}编码<br/>
  6.          * @param url
  7.          * @param files 文件表单域
  8.          * @param fields 非文件表单域
  9.          * @return JSONObject
  10.          * @throws Exception
  11.          * @exception
  12.          * @since  1.0.0
  13.          */
  14.         public static JSONObject sendMultipartDataToHttpServer(URL url,
  15.                         final Map<String, File> files, final Map<String, String> fields,
  16.                         final UsernamePasswordCredentials credentials) throws IOException ,JSONException,Exception{
  17.                 URL myurl = null;
  18.                 String queryString = "";
  19.                 // 其他的表单域
  20.                 if (fields != null) {
  21.                         for (Map.Entry<String, String> entry : fields.entrySet()) {
  22.                                 queryString += "&" + URLEncoder.encode(entry.getKey(),HTTP_ENCODING) + "="
  23.                                                 + URLEncoder.encode(entry.getValue(), HTTP_ENCODING);
  24.                         }
  25.                 }
  26.                 if (!queryString.equals("")) {
  27.                         queryString = queryString.replaceFirst("&", "?");
  28.                 } else {
  29.                 }
  30.  
  31.                 myurl = new URL(url.getProtocol(), url.getHost(),url.getPort(), url.getPath()
  32.                                 + queryString);
  33.                 HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
  34.                 conn.setConnectTimeout(UPLOAD_REQUEST_TIMEOUT);
  35.                 conn.setRequestMethod(HTTP_METHOD.POST.toString());
  36.                 conn.setDoInput(true);
  37.                 conn.setDoOutput(true);
  38.                 conn.setUseCaches(false);
  39.  
  40.                 String boundary = "laohuidi_" + java.util.UUID.randomUUID().toString()
  41.                                 + "_laohuidi";
  42.                 conn.setRequestProperty(
  43.                                                 "Accept",
  44.                                                 "image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,application/x-shockwave-flash,application/x-quickviewplus,*/*");
  45.                 conn.setRequestProperty("keep-alive", "300");
  46.                 conn.setRequestProperty(
  47.                                                 "user-agent",
  48.                                                 "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB6");
  49.                 conn.setRequestProperty("accept-language", "zh-cn,zh;q=0.5");
  50.                 conn.setRequestProperty("Connection", "Keep-Alive");
  51.                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
  52.  
  53.                 DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
  54.                 // 乱码问题 可以试下 PrintWriter out = new PrintWriter(new
  55.                 // OutputStreamWriter(connection.getOutputStream(),"utf-8"));
  56.                 dos = new DataOutputStream(conn.getOutputStream());
  57.                 int bytesRead, bytesAvailable, bufferSize;
  58.                 byte[] buffer;
  59.                 int maxBufferSize = IO_BUFFER_SIZE;
  60.                 String tem = "";
  61.                 if(files!=null)
  62.                 for (Map.Entry<String, File> entry : files.entrySet()){
  63.                         // 分隔符开头
  64.                         dos.writeBytes(TWO_HYPHENS + boundary + LINEND);
  65.                         // create a buffer of maximum size
  66.                         FileInputStream fileInputStream = new FileInputStream(entry.getValue());
  67.                         bytesAvailable = fileInputStream.available();
  68.                         bufferSize = Math.min(bytesAvailable, maxBufferSize);
  69.                         buffer = new byte[bufferSize];
  70.                         // read file and write it into form...
  71.                         bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  72.                         tem = entry.getValue().getName();
  73.                         dos.writeBytes("Content-Disposition:form-data;name=\""+entry.getKey()+"\";"+ "filename=\"");
  74.                         dos.writeUTF(tem);// 中文的文件名使用这里
  75.                         dos.writeBytes("\"" + LINEND);
  76.                         dos.writeBytes("Content-Type:image/jpg" + LINEND + LINEND);//类型的判断暂时不处理
  77.                         while (bytesRead > 0) {
  78.                                 dos.write(buffer, 0, bufferSize);
  79.                                 bytesAvailable = fileInputStream.available();
  80.                                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
  81.                                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  82.                         }
  83.                         // close streams
  84.                         fileInputStream.close();
  85.                         dos.writeBytes(LINEND);
  86.                 }
  87.                 // http 结束符
  88.                 dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS);
  89.                 dos.writeBytes(LINEND);
  90.  
  91.                 dos.flush();
  92.                 dos.close();
  93.                 // 返回类型
  94.                 String responseType = conn.getHeaderField("Content-Type");
  95.                 // 正常返回而且必须为json类型
  96.                 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK
  97.                                 && responseType != null
  98.                                 && responseType.indexOf(HTTP_JSON_TYPE) >= 0) {
  99.                         responseType = (convertStreamToString(conn.getInputStream()));
  100.  
  101.                 } else {
  102.                         responseType = "{}";
  103.                 }
  104.                 try{conn.disconnect();}catch(Exception e){}
  105.                 return new JSONObject(responseType);
  106.         }

相关内容