今天是学习android的第二个月多了,今天自学了如何通过URL类的方法向服务器获取源代码,但是在这中途碰到了很多问题
String path=ed.getText().toString().trim();
//2.2创建一个URL类的实例
URL url=new URL("http://www.baidu.com/");
//2.3调用HttpURLconn方法,用于发送或者接收
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//2.4设置发送get请求
conn.setRequestMethod("GET");
//2.5设置超时时间,是以毫秒为单位
conn.setConnectTimeout(1000*10);
//2.6拿到服务器响应码,200为请求成功
System.out.println(conn.getResponseCode());
//重新定向到被重定向的网站
String location = conn.getHeaderField("Location");
System.out.println("location "+location+"");
//4.为URLconn设置请求参数(请求方式,连接的超时时间等)
url = new URL(location);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(1000*10);
int code = conn.getResponseCode();
System.out.println(code);
另一个工具类的类型是传一个inputstearm流转换成string,内容如下
public static String readstearm(InputStream in) throws IOException {
//定义一个内存输出流
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int len=-1;
byte[] buffer=new byte[1024];//为1kb
while((len=in.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
String count=new String(baos.toByteArray());
in.close();
return count;
}
我一运行,就感觉会出错,果不其然点击按钮没有任何反应,倒是没有报错
debug一下,发现是获取服务器响应码的时候出了问题,它并不是我想要的200,而是不知名的302,于是乎百度了一下到底这302是何方神圣,百度到的比较官方的说法是
HTTP 状态码 3xx - 重定向 302 redirect: 302 代表暂时性转移(Temporarily Moved )。
大概意思应该就是被重定向了,后来问了一下老师,既然重定向了,那就直接重新获取就行了
通过String location = conn.getHeaderField("Location");来获取重定向的网址,再将它们放到子线程里面去
new Thread() {
public void run() {
try {
//2.1接收输入框的文字
String path=ed.getText().toString().trim();
//2.2创建一个URL类的实例
URL url=new URL("http://www.baidu.com/");
//2.3调用HttpURLconn方法,用于发送或者接收
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//2.4设置发送get请求
conn.setRequestMethod("GET");
//2.5设置超时时间,是以毫秒为单位
conn.setConnectTimeout(1000*10);
//2.6拿到服务器响应码,200为请求成功
System.out.println(conn.getResponseCode());
//重新定向到被重定向的网站
String location = conn.getHeaderField("Location");
System.out.println("location "+location+"");
url = new URL(location);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(1000*10);
int code = conn.getResponseCode();
System.out.println(code);
//2.7 200就代表请求成功了
if(code==200) {
//2.8 获取服务器返回的数据,是以流的方式返回的,由于流转换成字符串是一个常见的操作,所以我们将它封装成一个类
InputStream input = conn.getInputStream();
String read = Stearmtool.readstearm(input);
tv.setText(read);
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}.start();