不帶HttpEntity 的Volley 多部分請求
簡介
簡介簡介程式碼實作
package com.example.multipartvolley; // ... As before @Override protected void onCreate(Bundle savedInstanceState) { // ... As before byte[] fileData1 = getFileDataFromDrawable(context, R.drawable.ic_action_android); byte[] fileData2 = getFileDataFromDrawable(context, R.drawable.ic_action_book); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { // ... As before } catch (IOException e) { // ... As before } String url = "http://192.168.1.100/api/postfile"; MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { // ... As before } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // ... As before } }); // ... As before } // ... Remaining methods
MultipartActivity.java:
package com.example.multipartvolley; // ... As before @Override public String getBodyContentType() { return mMimeType; } @Override public byte[] getBody() throws AuthFailureError { return mMultipartBody; } // ... Remaining methods
MultipartRequest.java:
@Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); // Add your text parameters params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76"); params.put("name", "Angga"); params.put("location", "Indonesia"); return params; }
要在請求中包含文本數據,您可以重寫VolleyMultipartRequest 中的getParams() 方法:
結論 即使在HttpEntity被棄用之後,所提供的程式碼也提供了使用 Volley 發送多部分請求的實用解決方案。透過使用本文中描述的方法,開發人員可以輕鬆地將多個文件和文字資料 POST 到伺服器,而不需要複雜的 HttpEntity 實作。以上是棄用 HttpEntity 後如何使用 Volley 發送多部分請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!