gpt4 book ai didi

android - 是否可以在 android 上使用 volley 下载任何文件(pdf 或 zip)?

转载 作者:搜寻专家 更新时间:2023-11-01 08:21:52 25 4
gpt4 key购买 nike

如何使用 android volley 下载 pdf 文件或 zip 文件。使用字符串、JSON、图像或视频很容易工作。其他文件呢?

最佳答案

首先你必须创建你自己的自定义请求类

class InputStreamVolleyRequest extends Request<byte[]> {
private final Response.Listener<byte[]> mListener;
private Map<String, String> mParams;

//create a static map for directly accessing headers
public Map<String, String> responseHeaders ;

public InputStreamVolleyRequest(int method, String mUrl ,Response.Listener<byte[]> listener,
Response.ErrorListener errorListener, HashMap<String, String> params) {
// TODO Auto-generated constructor stub

super(method, mUrl, errorListener);
// this request would never use cache.
setShouldCache(false);
mListener = listener;
mParams=params;
}

@Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};


@Override
protected void deliverResponse(byte[] response) {
mListener.onResponse(response);
}

@Override
protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {

//Initialise local responseHeaders map with response headers received
responseHeaders = response.headers;

//Pass the response data here
return Response.success( response.data, HttpHeaderParser.parseCacheHeaders(response));
}
}

现在只需通过我们的带有 Request.Method.GET 的自定义类和您想要加载文件的 url 发送请求。

String mUrl= <YOUR_URL>;
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
@Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response!=null) {

FileOutputStream outputStream;
String name=<FILE_NAME_WITH_EXTENSION e.g reference.txt>;
outputStream = openFileOutput(name, Context.MODE_PRIVATE);
outputStream.write(response);
outputStream.close();
Toast.makeText(this, "Download complete.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
} ,new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);

关于android - 是否可以在 android 上使用 volley 下载任何文件(pdf 或 zip)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com