我用'com.loopj.android:android-async-http:1.4.9'
发出http请求。我使用BinaryHttpResponseHandler来获取图像,但我想将其发送到SD卡。我的代码是:
AsyncHttpUtils.getBinary(url, new BinaryHttpResponseHandler(allowedContentTypes) {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
Log.d(TAG,"getFile onSuccess"+binaryData.length);
String tempPath = "Download";
// 文件地址
String filePath = tempPath +"/"+ "oktest" + ".jpg";
FileUtils fileUtils = new FileUtils();
InputStream inputstream = new ByteArrayInputStream(binaryData);
if (inputstream != null) {
fileUtils.write2SDFromInput(filePath, inputstream);
try {
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
Log.d(TAG,"getFile onFailure");
}
});
如何将二进制文件发送到SD卡?
你不需要用ByteArrayInputStream
或FileUtils
,只需FileOutputStream
即可。
AsyncHttpUtils.getBinary(url, new BinaryHttpResponseHandler(allowedContentTypes) {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
Log.d(TAG,"getFile onSuccess "+binaryData.length);
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "yourFileName.jpg");
try (FileOutputStream os = new FileOutputStream(file)) {
os.write(binaryData);
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
Log.d(TAG,"getFile onFailure");
}
});