当前位置:K88软件开发文章中心编程语言APP编程Android01 → 文章内容

7.3.1 Android 文件上传

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-12 6:26:49

httppost = new HttpPost(path); httppost.setEntity(entity); //看作是浏览器 HttpClient httpclient = new DefaultHttpClient(); //发送post请求 HttpResponse response = httpclient.execute(httppost); return readStream(response.getEntity().getContent()); } /** * 发送请求 * @param path 请求路径 * @param params 请求参数 key为参数名称 value为参数值 * @param encode 请求参数的编码 */ public static byte[] post(String path, Map<String, String> params, String encode) throws Exception { //String params = "method=save&name="+ URLEncoder.encode("老毕", "UTF-8")+ "&age=28&";//需要发送的参数 StringBuilder parambuilder = new StringBuilder(""); if(params!=null && !params.isEmpty()) { for(Map.Entry<String, String> entry : params.entrySet()) { parambuilder.append(entry.getKey()).append("=") .append(URLEncoder.encode(entry.getValue(), encode)).append("&"); } parambuilder.deleteCharAt(parambuilder.length()-1); } byte[] data = parambuilder.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置允许对外发送请求参数 conn.setDoOutput(true); //设置不进行缓存 conn.setUseCaches(false); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("POST"); //下面设置http请求头 conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Connection", "Keep-Alive"); //发送参数 DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data);//把参数发送出去 outStream.flush(); outStream.close(); if(conn.getResponseCode()==200) { return readStream(conn.getInputStream()); } return null; } /** * 读取流 * @param inStream * @return 字节数组 * @throws Exception */ public static byte[] readStream(InputStream inStream) throws Exception { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while( (len=inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } } 偶然发现一篇以前转载的,可以搭配着上面的看看...:使用HttpConnection上传mp3文件本节小结:本节还是直接无视吧...关于文件上传等进阶部分直接教大家用第三方算了,项目中需要用到第三方直接复制1的代码,导入个android-async-http即可!

上一页  [1] [2] [3] 


7.3.1 Android 文件上传