package com.example.httpurlconnection;import android.os.Handler;import android.webkit.WebView;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import javax.net.ssl.HttpsURLConnection;/** * Created by Cal-Lightman on 2017/4/13. */public class HttpThread { private String url; private WebView webView; private Handler handler; public HttpThread(String url, WebView webView, Handler handler) { this.url = url; this.webView = webView; this.handler = handler; } public void run() { try { URL httpUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) httpUrl.openConnection(); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); final StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String string; while ((string = bufferedReader.readLine()) != null) { stringBuffer.append(string); } handler.post(new Runnable() { @Override public void run() { webView.loadData(stringBuffer.toString(), "text/html;charset=utf-8", null); } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}package com.example.httpurlconnection;import android.os.Bundle;import android.os.Handler;import android.support.v7.app.AppCompatActivity;import android.webkit.WebSettings;import android.webkit.WebView;import android.widget.ImageView;import static android.provider.ContactsContract.CommonDataKinds.Website.URL;public class MainActivity extends AppCompatActivity { private WebView webView; private Handler handler = new Handler(); private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.webView); imageView = (ImageView) findViewById(R.id.imageView); new HttpThread("http://www.baidu.com/", webView, handler).start; }}
- 3 回答
- 0 关注
- 1875 浏览
添加回答
举报
0/150
提交
取消