ITPub博客

首页 > 应用开发 > > 这个HttpThread为什么不能.start();

这个HttpThread为什么不能.start();

作者:yellowduck007 时间:2019-11-21 16:17:53 0 删除 编辑

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;

}

}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2611/viewspace-3129692/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    88
  • 访问量
    983