码迷,mamicode.com
首页 > Web开发 > 详细

PhoneHttp

时间:2017-02-24 19:43:51      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:content   app   widget   super   void   port   技术   textview   play   

package com.example.phonehttp;

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 android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

String str;
Handler handler = null;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv = (TextView) findViewById(R.id.tv);

handler = new Handler();

GetThread getThread = new GetThread();
getThread.start();

}

class GetThread extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub
try {
//URL url = new URL("http://192.168.190.1:8080/play_1/a.txt");
URL url = new URL("https://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("请求url失败");
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));

StringBuffer sb = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
str = sb.toString();
handler.post(runnableUi);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

};

Runnable runnableUi = new Runnable() {
@Override
public void run() {
// 更新界面
tv.setText("the Content is:" + str);
}

};

}

 

android通信一定要用线程来实现!  android通信一定要用线程来实现!  android通信一定要用线程来实现!   重要的事情说三遍!

技术分享

 

PhoneHttp

标签:content   app   widget   super   void   port   技术   textview   play   

原文地址:http://www.cnblogs.com/lhang55/p/6439779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!