httpurlconnection

public class HomeHotSpotFragment extends Fragment {
WebView mWebView;
Button mButton;
TextView mTextView;


public HomeHotSpotFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home_hot_spot, container, false);
mWebView = (WebView) v.findViewById(R.id.baidu);
mButton = (Button) v.findViewById(R.id.web);
mTextView = (TextView) v.findViewById(R.id.sec);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//启动子线程方法1
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
HttpUrlConnectionGet();
}
});
mThread.start();
//启动子线程方法2
/*new Thread(new Runnable() {
@Override
public void run() {
HttpUrlConnectionGet();
}
}).start();*/
}
});
return v;
}
private void HttpUrlConnectionGet(){
HttpURLConnection mHttpURLConnection = null;
InputStream mInputStream;
StringBuilder mStringBuilder = new StringBuilder();
try {
//定义url网址"http://baidu.com"
URL mUrl = new URL("http://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1&word=%E6%9E%97%E4%B8%B9");
mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
//设置时间,链接,请求超时时间
mHttpURLConnection.setConnectTimeout(5*1000);
mHttpURLConnection.setReadTimeout(5*1000);
//设置请求码,为百度是可以不用
mHttpURLConnection.setRequestProperty("apikey","3457f565f8ed592707432f9d44440f96");
//链接
mHttpURLConnection.connect();
if (mHttpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){//不为空
mInputStream = mHttpURLConnection.getInputStream();//获得输入流
byte[] bytes = new byte[1024];
int i;
while ((i = mInputStream.read(bytes)) != -1){
mStringBuilder.append(new String(bytes,0,i,"utf-8"));
}
mInputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (mHttpURLConnection != null){
mHttpURLConnection.disconnect();
}
}
//信息交互,子线程不能控制view,获得的信息要交给主线程,前一个1为识别码,后面的是内容
Message message = mHandler.obtainMessage(1,mStringBuilder.toString());
mHandler.sendMessage(message);
}
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg != null && msg.what == 1){
String s = (String) msg.obj;
//设置格式
mWebView.getSettings().setDefaultTextEncodingName("utf-8");
//设置内容的事件为可执行的
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadDataWithBaseURL(null,s,"text/html","utf-8",null);
}
}
};

}
posted @ 2016-09-20 16:30  极品草草  阅读(420)  评论(0编辑  收藏  举报