标签:
1 public String startToUpload(String urlStr, File file, 2 String uploadType) { 3 4 HttpURLConnection conn = null; 5 BufferedReader bufferedReader = null; 6 InputStreamReader inputStreamReader = null; 7 String BOUNDARY = "---------------------------"; // boundary就是request头和上传文件内容的分隔符 8 try { 9 URL url = new URL(urlStr); 10 conn = (HttpURLConnection) url.openConnection(); 11 conn.setConnectTimeout(5000); 12 conn.setReadTimeout(30000); 13 conn.setDoOutput(true); 14 conn.setDoInput(true); 15 conn.setUseCaches(false); 16 conn.setRequestMethod("POST"); 17 conn.setRequestProperty("Connection", "Keep-Alive"); 18 conn.setRequestProperty("User-Agent", 19 "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); 20 conn.setRequestProperty("Content-Type", 21 "multipart/form-data; boundary=" + BOUNDARY); 22 23 OutputStream out = new DataOutputStream(conn.getOutputStream()); 24 25 String filename = file.getName(); 26 27 StringBuffer strBuf = new StringBuffer(); 28 strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); 29 strBuf.append("Content-Disposition: form-data; name=\"file\"; filename=\"" 30 + filename + "\"\r\n"); 31 strBuf.append("Content-Type:" + uploadType + "\r\n\r\n"); 32 33 out.write(strBuf.toString().getBytes()); 34 35 DataInputStream in = new DataInputStream(new FileInputStream(file)); 36 int bytes = 0; 37 byte[] bufferOut = new byte[1024]; 38 while ((bytes = in.read(bufferOut)) != -1) { 39 out.write(bufferOut, 0, bytes); 40 } 41 in.close(); 42 43 byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 44 out.write(endData); 45 out.flush(); 46 out.close(); 47 48 // 读取返回数据 49 StringBuffer strBuf2 = new StringBuffer(); 50 inputStreamReader = new InputStreamReader(conn.getInputStream(), 51 "UTF-8"); 52 bufferedReader = new BufferedReader(inputStreamReader); 53 String line = null; 54 while ((line = bufferedReader.readLine()) != null) { 55 strBuf2.append(line).append("\n"); 56 } 57 58 JSONObject jsonArray = JSONObject.fromObject(strBuf2.toString()); 59 60 boolean uploadSuccess = jsonArray.getBoolean("returnCode"); 61 62 if (uploadSuccess) { 63 return ""; 64 } 65 66 urlStr = jsonArray.getString("resultMsg"); 67 } catch (Exception e) { 68 e.printStackTrace(); 69 return e.getMessage(); 70 } finally { 71 try { 72 if (conn != null) { 73 conn.disconnect(); 74 } 75 if (inputStreamReader != null) { 76 inputStreamReader.close(); 77 } 78 if (bufferedReader != null) { 79 bufferedReader.close(); 80 } 81 } catch (IOException e) { 82 e.printStackTrace(); 83 } 84 } 85 return urlStr; 86 } 87
标签:
原文地址:http://www.cnblogs.com/huadoumi/p/4772719.html