1.在android中使用HttpURLConnection访问百度主页,并显示出来
直接贴代码图片了
MainActivity:
MainActivity_xml:
AndroidManifest.xml
继承线程类(主要的处理类):
//继承线程类
public class WebThread extends Thread {
private String url;
private WebView webView;
private Handler handler;
public WebThread(String url,WebView webView,Handler handler){
this.url=url;
this.webView=webView;
this.handler=handler;
}
@Override
public void run() {
try {
URL httpurl=new URL(url);//设置请求的url
HttpURLConnection conn= (HttpURLConnection) httpurl.openConnection();//获取url的连接
conn.setConnectTimeout(50000);//设置超时时间
conn.setRequestMethod("GET");//设置请求的方式
InputStream in=conn.getInputStream();//获取输入流
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String str;
final StringBuffer buffer=new StringBuffer();
while((str=reader.readLine())!=null){//循环读取数据
buffer.append(str);
}
handler.post(new Runnable() {
@Override
public void run() {//将数据输出
webView.loadData(buffer.toString(),"text/html;charset=utf-8",null);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2..在android中使用HttpURLConnection访问一张图片资源,并显示出来
MainActivity:
MaimActivity.xml:
AndroidManifest.xml:
一定要记得加权限
继承线程的处理方法:
public class ImageThread extends Thread {
private String url;
private ImageView image;
private Handler handler;
public ImageThread(String url,ImageView image,Handler handler){
this.url=url;
this.image=image;
this.handler=handler;
}
@Override
public void run() {
File file=null;
try {
/**
* 1.获取到请求路径
* 2.获取到连接
* 3.设置请求而方式
* 4.设置超时时间
* 5.获取输入流
* 6.将输入流中的信息写入到文件
* 7.更新UI
*/
URL hhtpurl=new URL(url);
HttpURLConnection conn= (HttpURLConnection) hhtpurl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream in=conn.getInputStream();//获取输入流
File path= Environment.getExternalStorageDirectory();//获取到内置文件夹
String filename=String.valueOf(System.currentTimeMillis());//获取当前是作为文件名字
file=new File(path,filename+".jpg");//创建图片文件
FileOutputStream out=new FileOutputStream(file);//创建文件输出流
byte[] bt=new byte[1024];
int len=-1;
while ((len=in.read(bt))!=-1){
out.write(bt,0,len);//循环写入文件
}
final Bitmap bitmap= BitmapFactory.decodeFile(file.getAbsolutePath());
handler.post(new Runnable() {
@Override
public void run() {
image.setImageBitmap(bitmap);//设置获取到的图片
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}