首页 > 学院 > 开发设计 > 正文

HttpURLConnection替代apache httpclient上传文件

2019-11-09 14:10:31
字体:
来源:转载
供稿:网友
Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead.apache httpclient上传文件非常方便,通过HttPRequestBase.setEntity(MultipartEntity)File uploadFile = new File(mUploadFilePath);MultipartEntity multipart = new MultipartEntity();multipart.addPart(mFilePartName, new FileBody(uploadFile, uploadFile.getName()));HttpPost post = new HttpPost("url");post.setEntity(multipart);HttpURLConnection中我们也借助MultipartEntity,而在Android 6.0上要使用这个类的话,我们需要在gradle中配置:useLibrary ‘org.apache.http.legacy’ //Android 6.0 release removes support for the Apache HTTP clientFile uploadFile = new File(mUploadFilePath);MultipartEntity multipart = new MultipartEntity();multipart.addPart(mFilePartName, new FileBody(uploadFile, uploadFile.getName()));HttpURLConnection connection = new URL("url").openConnection();connection.setRequestMethod("POST");connection.setDoOutput(true);Header type = multipart.getContentType();if (type != null) { connection.addRequestProperty(type.getName(), type.getValue());}Header encoding = multipart.getContentEncoding();if (encoding != null) { connection.addRequestProperty(encoding.getName(), encoding.getValue());}if (multipart.isChunked() || multipart.getContentLength() < 0) { connection.setChunkedStreamingMode(0);} else if (multipart.getContentLength() <= 8192) { // Buffer short, fixed-length request bodies. This costs memory, but permits the request // to be transparently retried if there is a connection failure. connection.addRequestProperty("Content-Length", Long.toString(multipart.getContentLength()));} else { connection.setFixedLengthStreamingMode((int) multipart.getContentLength());}OutputStream out = connection.getOutputStream();multipart.writeTo(out);out.close();
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表