Volley 是一個流行的 Android 庫,用於發出 HTTP 請求。在早期的 API 版本中,HttpEntity 與 Volley 結合使用進行多部分錶單資料提交。然而,隨著 API 22 中 HttpEntity 的棄用以及 API 23 中的完全刪除,開發人員面臨挑戰。
在本文中,我們將示範一個在不使用HttpEntity。提供的程式碼可讓您上傳多個文件和文字資料。
此處介紹的實作由兩個類別組成:MultipartActivity 和 MultipartRequest。 MultipartActivity 處理多部分錶單資料的準備,而 MultipartRequest 擴展了 Volley 的 Request 類別並重寫了處理多部分正文和處理伺服器回應的必要方法。
要使用此解決方案,請依照下列步驟操作:
MultipartActivity.java:
import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.Toast; import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.VolleyError; import com.example.multipartvolley.MultipartRequest; import com.example.multipartvolley.VolleySingleton; import java.util.HashMap; import java.util.Map; public class MultipartActivity extends Activity { private Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Assuming you have prepared file data in fileData1 and fileData2 String url = "http://192.168.1.100/api/postfile"; MultipartRequest multipartRequest = new MultipartRequest(url, null, "multipart/form-data", multipartBody, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { Toast.makeText(context, "Upload successfully!", Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, "Upload failed!\r\n" + error.toString(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("text_field1", "Value for text field 1"); params.put("text_field2", "Value for text field 2"); return params; } @Override protected Map<String, DataPart> getByteData() { Map<String, DataPart> params = new HashMap<>(); params.put("file_name1", new DataPart("file_name1.txt", "file content 1".getBytes(), "text/plain")); params.put("file_name2", new DataPart("file_name2.png", fileData1, "image/png")); return params; } }; VolleySingleton.getInstance(context).addToRequestQueue(multipartRequest); } }
Multi partRequest.java:
import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import java.util.HashMap; import java.util.Map; class MultipartRequest extends Request<NetworkResponse> { private final Response.Listener<NetworkResponse> mListener; private final Response.ErrorListener mErrorListener; private Map<String, String> mHeaders; private Map<String, DataPart> mByteData; MultipartRequest(String url, Map<String, String> headers, String contentType, Map<String, DataPart> byteData, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) { super(Method.POST, url, errorListener); this.mListener = listener; this.mErrorListener = errorListener; this.mHeaders = headers; this.mByteData = byteData; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return mHeaders != null ? mHeaders : super.getHeaders(); } @Override public String getBodyContentType() { return "multipart/form-data; boundary=" + getBoundary(); } @Override public byte[] getBody() throws AuthFailureError { return encodeMultipartData(mByteData, getBoundary()); } private String getBoundary() { return Long.toHexString(System.currentTimeMillis()); } @Override protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) { try { return Response.success( response, HttpHeaderParser.parseCacheHeaders(response)); } catch (Exception e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(NetworkResponse response) { mListener.onResponse(response); } @Override public void deliverError(VolleyError error) { mErrorListener.onErrorResponse(error); } protected static byte[] encodeMultipartData(Map<String, DataPart> dataParts, String boundary) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { for (Map.Entry<String, DataPart> entry : dataParts.entrySet()) { dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + "; filename=\"" + entry.getValue().getFileName() + "\"" + lineEnd); dos.writeBytes(String.format("Content-Type: %s%s", entry.getValue().getType(), lineEnd)); dos.writeBytes(lineEnd); dos.write(entry.getValue().getContent()); dos.writeBytes(lineEnd); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } } class DataPart { private String fileName; private byte[] content; private String type; DataPart(String fileName, byte[] content, String type) { this.fileName = fileName; this.content = content; this.type = type; } String getFileName() { return fileName; } byte[] getContent() { return content; } String getType() { return type; } } }
此程式碼處理多部分錶單資料請求,您可以將檔案和文字參數安全地傳遞到伺服器。需要注意的是,最終程式碼不適合生產使用,應根據您的特定要求進行修改。
以上是如何在不使用 HttpEntity 的情況下使用 Volley 發出多部分 POST 請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!