访问网络先加权限
4.0 版本以后 不允许在主线程 请求网络资源
HttpURLConnection conn= url.openConnection();
conn.setRequest("get");//设置请求方式
conn.setRequestTimeout(5000)//五秒没回应则请求超时
conn.setReadTimeout(5000)// 当请求内容过程中网络中断、五秒内重新连接上则不超时
conn.setRequestProperty(这里是请求的参数 头信息等);
{//post请求的时候需要额外加的参数
Strng data = "username="+username+"&password=”+password;
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",data.legth()+"");
//post 的方式实际上是浏览器把数据写给服务器
conn.setDoOutput(true);//允许写入数据
OutputStream os = conn.getOutputStream();
os.write(data.getBytes()); //写入数据
}
conn.getResponseCode()// 返回码 200 成功、404没找到。。。
InputStream is = conn.getinputStream();// 得到返回的资源流
Bitmap bitmap = BitmapFactory.decodeStream(is);
2.) 请求网页资源乱码
应该是资源的编码格式 并非默认的 utf-8
可以获取网页数据
判断网页数据是否包含utf-8或者 gb2113 等等
则转换资源编码格式
String str = new String(result,"gb2312");
3.)向服务器端发送数据时也要注意数据的编码格式
参数 username 要转换一下 URLEncoder.encode(username);
URLEncoder.encode(String) 的实现默认添加了utf-8参数
URLEncoder.encode(string,"utf-8“)