这清楚地表明,在获得响应后,媒体文件URL将被收到客户端。我的问题是如何使用我无法访问的网址下载文件,直到我收到回复?有没有可能在获取网址的同时下载文件或者收到网址然后下载文件?
我被困在这里,任何人都可以简单解释一下这里的解决方案吗?
任何帮助表示赞赏!
您需要在模型中解析Json。
然后,您可以获取url属性并将其下载到文件系统。您可以使用HttpUrlConnection执行此操作,或者如果您希望将Picasso库与Target Picasso一起使用并将其下载到文件系统中。
让我举个例子。
使用毕加索:
public static void downloadImageWithPicasso(Context context, String url) {
Picasso.with(context)
.load(your_url_from_model)
.into(saveUsingTarget(url));
}
private static Target saveUsingTarget(final String url){
Target target = new Target(){
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + url);
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
ostream.flush();
ostream.close();
} catch (IOException e) {
Log.e("IOException", e.getLocalizedMessage());
}
}
}).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
return target;
}
使用HttpUrlConnection
public void downloadImageWithUrlConnection(){
try{
URL url = new URL("your_url_from_model");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdCardPath = Environment.getExternalStorageDirectory().getAbsoluteFile();
String filename = "file_name.png";
File file = new File(sdCardPath,filename);
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ){
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
重要说明:如果要使用HttpURLConnection选项,则需要在后台线程中运行它。
我希望这可以帮助你。