通过项目来介绍,直接上代码
先创建一个HttpThread类
import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Agree on 2017/8/10. */ public class HttpThread extends Thread { private WebView webView; private String url; private Handler handler; private ImageView img; public HttpThread(String url,WebView webView,Handler handler){ this.url=url; this.webView=webView; this.handler=handler; } public HttpThread(String url,ImageView img,Handler handler){ this.url=url; this.img=img; this.handler=handler; } @Override public void run() { try { URL httpUrl=new URL(url); HttpURLConnection connection= (HttpURLConnection) httpUrl.openConnection(); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); final StringBuffer sb=new StringBuffer(); BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream())); String str; while ((str=reader.readLine())!=null){ sb.append(str); } handler.post(new Runnable() { @Override public void run() { webView.loadData(sb.toString(),"text/html;charset=utf-8",null); } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.run(); } }主Activity中的代码
public class MainActivity extends AppCompatActivity { private WebView webView; private ImageView img; private Handler handler=new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.webView); img = (ImageView) findViewById(R.id.imageView); new HttpThread("http://www.vko.cn",webView,handler).start(); } }用HttpUrlConnection来加载图片
URL httpUrl=new URL(url); HttpURLConnection connection= (HttpURLConnection) httpUrl.openConnection(); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); connection.setDoInput(true); InputStream in=connection.getInputStream(); FileOutputStream out=null; File downLoadFile=null; String fileName= String.valueOf(System.currentTimeMillis()); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File parent=Environment.getExternalStorageDirectory(); downLoadFile=new File(parent,fileName); out=new FileOutputStream(downLoadFile); } byte[] b=new byte[2*1024]; int len; if (out!=null){ while ((len=in.read(b))!=-1){ out.write(b,0,len); } } final Bitmap bitmap= BitmapFactory.decodeFile(downLoadFile.getAbsolutePath()); handler.post(new Runnable() { @Override public void run() { img.setImageBitmap(bitmap); } });