使用POST和HttpURLConnection發(fā)送文件因為Android開發(fā)者推薦使用HttpURLConnection類時,我想知道是否有人可以提供一個很好的示例,說明如何通過POST將位圖“文件”(實際上是內(nèi)存中的流)發(fā)送到ApacheHTTP服務(wù)器。我對cookie或身份驗證或任何復(fù)雜的東西不感興趣,但我只想有一個可靠的邏輯實現(xiàn)。我在這里看到的所有例子看上去都更像是“讓我們試試這個,也許它是有用的”?,F(xiàn)在,我有這樣的代碼: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應(yīng)該只顯示AlertDialog(如果URL無效?)?,F(xiàn)在,假設(shè)我生成了如下所示的位圖:Bitmap image = this.getBitmap()中派生的控件內(nèi)部。View我想通過郵寄出去。實現(xiàn)這一目標(biāo)的適當(dāng)程序是什么?我需要使用哪些類?我能用一下嗎HttpPost就像在這個例子?如果是這樣,我將如何構(gòu)造InputStreamEntity我的位圖?我會發(fā)現(xiàn),要求首先將位圖存儲在設(shè)備上的文件中是令人反感的。我還應(yīng)該提到,我確實需要將原始位圖的每個未更改的像素發(fā)送到服務(wù)器,因此我無法將其轉(zhuǎn)換為JPEG。
3 回答

呼如林
TA貢獻(xiàn)1798條經(jīng)驗 獲得超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線程中以獲得響應(yīng)。
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.
添加回答
舉報
0/150
提交
取消