首页 > 代码库 > PhoneHttp

PhoneHttp

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