使用POST和HttpURLConnection发送文件因为Android开发者推荐使用HttpURLConnection类时,我想知道是否有人可以提供一个很好的示例,说明如何通过POST将位图“文件”(实际上是内存中的流)发送到ApacheHTTP服务器。我对cookie或身份验证或任何复杂的东西不感兴趣,但我只想有一个可靠的逻辑实现。我在这里看到的所有例子看上去都更像是“让我们试试这个,也许它是有用的”。现在,我有这样的代码:URL url;HttpURLConnection urlConnection = null;try {
url = new URL("http://example.com/server.cgi");
urlConnection = (HttpURLConnection) url.openConnection();} catch (Exception e) {
this.showDialog(getApplicationContext(), e.getMessage());}finally {
if (urlConnection != null)
{
urlConnection.disconnect();
}}其中,showDialog应该只显示AlertDialog(如果URL无效?)。现在,假设我生成了如下所示的位图:Bitmap image = this.getBitmap()中派生的控件内部。View我想通过邮寄出去。实现这一目标的适当程序是什么?我需要使用哪些类?我能用一下吗HttpPost就像在这个例子?如果是这样,我将如何构造InputStreamEntity我的位图?我会发现,要求首先将位图存储在设备上的文件中是令人反感的。我还应该提到,我确实需要将原始位图的每个未更改的像素发送到服务器,因此我无法将其转换为JPEG。
3 回答
慕容3067478
TA贡献1773条经验 获得超3个赞
MultipartUtility
MultipartUtility.java
public class MultipartUtility { private final String boundary; private static final String LINE_FEED = "\r\n"; private HttpURLConnection httpConn; private String charset; private OutputStream outputStream; private PrintWriter writer; /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * * @param requestURL * @param charset * @throws IOException */ public MultipartUtility(String requestURL, String charset) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); Log.e("URL", "URL : " + requestURL.toString()); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); httpConn.setRequestProperty("Test", "Bonjour"); outputStream = httpConn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(String name, String value) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"") .append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append( LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } /** * Adds a upload file section to the request * * @param fieldName name attribute in <input type="file" name="..." /> * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); writer.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * * @param name - name of the header field * @param value - value of the header field */ public void addHeaderField(String name, String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public String finish() throws IOException { StringBuffer response = new StringBuffer(); writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response.toString(); }}
upload
file
注意:将下面的代码放在非UI线程中以获得响应。
String charset = "UTF-8";String requestURL = "YOUR_URL";MultipartUtility multipart = new MultipartUtility(requestURL, charset); multipart.addFormField("param_name_1", "param_value");multipart.addFormField("param_name_2", "param_value"); multipart.addFormField("param_name_3", "param_value");multipart.addFilePart("file_param_1", new File(file_path)); String response = multipart.finish(); // response from server.
- 3 回答
- 0 关注
- 365 浏览
添加回答
举报
0/150
提交
取消