您的位置:首页 > 理论基础 > 计算机网络

用HttpUrlConnection来下载文件信息

2017-11-09 15:33 288 查看
public class LoadToFile extends Activity implements View.OnClickListener {

private static final String TAG = "LoadToFile";

private Button mBtn;
private ImageView mImg;
private String url = "http://image.tianjimedia.com/uploadImages/2014/289/01/IGS09651F94M.jpg";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadfile);
initView();
}

private void initView() {
mBtn = (Button) findViewById(R.id.btn);
mBtn.setOnClickListener(this);
mImg = (ImageView) findViewById(R.id.img);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
new Thread(new Runnable() {
@Override
public void run() {
httpRequestGet(url);
}
}).start();
break;
default:
break;
}
}

/**
* get请求
* @param loadUrl
*/
private void httpRequestGet(String loadUrl){
try {
URL url = new URL(loadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setReadTimeout(30*1000);
connection.setConnectTimeout(10*1000);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
FileOutputStream fos = new FileOutputStream(new File(getFilePath()));
InputStream inputStream = connection.getInputStream();
byte [] length = new byte[1024];
int l = 0;
while ((l = inputStream.read(length)) != -1){
fos.write(length , 0 , l);
}
fos.flush();
fos.close();
}else {
Log.e(TAG, "httpRequestGet--->网络请求失败");
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 获得存储路径
* @return
*/
private String getFilePath(){
if (hasSDCard()){
File file = null;
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/what/haha.jpeg";
file = new File(filePath);
if (!file.exists()){
file.getParentFile().mkdirs();
}else {
file.delete();
}
return file.getPath();
}else {
return null;
}
}

/**
* 判断sd卡是否存在
* @return
*/
private boolean hasSDCard(){
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}else {
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: