发送GET请求
URL url = new URL(path);
//获取连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置连接属性
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//建立连接,获取响应吗
if(conn.getResponseCode() == 200){
}
获取服务器返回的流,从流中把html源码读取出来
由于构建字符串String,可以通过new String(byte[] )来构建,而ByteArrayOutputStream 可以调用.toByteArray(),能够将流直接转换为字节数组
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = is.read(b)) != -1){
//把读到的字节先写入字节数组输出流中存起来
bos.write(b, 0, len);
}
//把字节数组输出流中的内容转换成字符串
//默认使用utf-8
text = new String(bos.toByteArray());
乱码的处理
乱码的出现是因为服务器和客户端码表不一致导致//手动指定码表
text = new String(bos.toByteArray(), "utf-8");
核心代码
public class MainActivity extends Activity {
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText((String)msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
Thread t = new Thread(){
@Override
public void run() {
String path = "http://192.168.1.103:8080/baidu.html";
try {
URL url = new URL(path);
//获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//先建立连接,然后获取响应码
if(conn.getResponseCode() == 200){
//拿到服务器返回的输入流,流里的数据就是html的源文件
InputStream is = conn.getInputStream();
//从流里把文本数据取出来
String text = Utils.getTextFromStream(is);
//发送消息,让主线程刷新ui,显示源文件
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
}
从流中获取到字符串
public class Utils {
public static String getTextFromStream(InputStream is){
byte[] b = new byte[1024];
int len = 0;
//创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while((len = is.read(b)) != -1){
bos.write(b, 0, len);
}
//把字节数组输出流里的数据转换成字节数组
String text = new String(bos.toByteArray());
return text;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}