http 上传文件的方法
/** * * sendMultipartDataToHttpServer * 使用post方法请求web服务器,并且当表单数据为:multipart/form-data格式。http请求使用{@link#HTTP_ENCODING}编码<br/> * 返回json数据,支持文件名中文上传和多文件上传,不支持断点上传,要正确编码服务端返回{@link#HTTP_ENCODING}编码<br/> * @param url * @param files 文件表单域 * @param fields 非文件表单域 * @return JSONObject * @throws Exception * @exception * @since 1.0.0 */ public static JSONObject sendMultipartDataToHttpServer(URL url, final Map<String, File> files, final Map<String, String> fields, final UsernamePasswordCredentials credentials) throws IOException ,JSONException,Exception{ URL myurl = null; String queryString = "";
// 其他的表单域 if (fields != null) { for (Map.Entry<String, String> 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<String, File> 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); }
标签:
android开发
, http 上传的方法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架