/** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * @param actionUrl * @param params * @param files * @return * @throws IOException */ public static String post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--" , LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8";
URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(5 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); }
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if(files!=null){ int i = 0; for (Map.Entry<String, File> file: files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file"+(i++)+"\"; filename=\""+file.getKey()+"\""+LINEND); sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); }
is.close(); outStream.write(LINEND.getBytes()); } } //请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush();
//得到响应码 int res = conn.getResponseCode(); InputStream in = null; if (res == 200) { in = conn.getInputStream(); int ch; StringBuilder sb2 = new StringBuilder(); while ((ch = in.read()) != -1) { sb2.append((char) ch); } } return in == null ? null : in.toString(); }
最简单的PHP测试代码:
if($_FILES){ foreach($_FILES as $v){ copy($v[tmp_name], $v[name]); } } -----------------------------------------------------------------------------------
/** * * sendMultipartDataToHttpServer * 使用post方法请求web服务器,并且当表单数据为:multipart/form-data格式。http请求使用 {@link#HTTP_ENCODING}编码
* @param url * @param files 文件表单域 * @param fields 非文件表单域 * @return JSONObject * @throws Exception * @exception * @since 1.0.0 */ public static JSONObject sendMultipartDataToHttpServer(URL url, final Map files, final Map fields, final UsernamePasswordCredentials credentials) throws IOException ,JSONException,Exception{ URL myurl = null; String queryString = “”; // 其他的表单域 if (fields != null) { for (Map.Entry entry : fields.entrySet()) { queryString += “&” + URLEncoder.encode(entry.getKey(),HTTP_ENCODING) + “=” + URLEncoder.encode(entry.getValue(), HTTP_ENCODING); } } if (!queryString.equals(”")) { queryString = queryString.replaceFirst(”&”, “?”); } else { }
myurl = new URL(url.getProtocol(), url.getHost(),url.getPort(), url.getPath() + queryString); HttpURLConnection conn = (HttpURLConnection) myurl.openConnection(); conn.setConnectTimeout(UPLOAD_REQUEST_TIMEOUT); conn.setRequestMethod(HTTP_METHOD.POST.toString()); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false);
String boundary = “laohuidi_” + java.util.UUID.randomUUID().toString() + “_laohuidi”; conn.setRequestProperty( “Accept”, “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,*/*”); conn.setRequestProperty(”keep-alive”, “300″); conn.setRequestProperty( “user-agent”, “Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB6″); conn.setRequestProperty(”accept-language”, “zh-cn,zh;q=0.5″); conn.setRequestProperty(”Connection”, “Keep-Alive”); conn.setRequestProperty(”Content-Type”, “multipart/form-data;boundary=”+ boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); // 乱码问题 可以试下 PrintWriter out = new PrintWriter(new // OutputStreamWriter(connection.getOutputStream(),”utf-8″)); dos = new DataOutputStream(conn.getOutputStream()); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = IO_BUFFER_SIZE; String tem = “”; if(files!=null) for (Map.Entry entry : files.entrySet()){ // 分隔符开头 dos.writeBytes(TWO_HYPHENS + boundary + LINEND); // create a buffer of maximum size FileInputStream fileInputStream = new FileInputStream(entry.getValue()); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form… bytesRead = fileInputStream.read(buffer, 0, bufferSize); tem = entry.getValue().getName(); dos.writeBytes(”Content-Disposition:form-data;name=\”"+entry.getKey()+”\”;”+ “filename=\”"); dos.writeUTF(tem);// 中文的文件名使用这里 dos.writeBytes(”\”" + LINEND); dos.writeBytes(”Content-Type:image/jpg” + LINEND + LINEND);//类型的判断暂时不处理 while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // close streams fileInputStream.close(); dos.writeBytes(LINEND); } // http 结束符 dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS); dos.writeBytes(LINEND);
dos.flush(); dos.close(); // 返回类型 String responseType = conn.getHeaderField(”Content-Type”); // 正常返回而且必须为json类型 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK && responseType != null && responseType.indexOf(HTTP_JSON_TYPE) >= 0) { responseType = (convertStreamToString(conn.getInputStream()));
} else { responseType = “{}”; } try{conn.disconnect();}catch(Exception e){} return new JSONObject(responseType); } --------------------------------------------------------------------
|