android基础04
1.利用HttpURLConnection对象,我们可以从网络中获取网页数据 URL url = new URL("http://www.sohu.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5* 1000);//设置连接超时 conn.setRequestMethod(“GET”);//以get方式发起请求 if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败"); InputStream is = conn.getInputStream();//得到网络返回的输入流
2.android中默认的编码是Utf-8
3.Context.getResources().getString(R.id.name); 获取strings.xml文件 Resources 节点下 String节点中属性为 name 的值
4.TextView.setText(int id); 当设置的text为int类型时,一定要注意,否则该方法去找资源id TextView.setText(String text); 如果text为int类型,那么就将int类型的数据转换为String类型
5.BitmapFactory.decodeStream(InputStream is);直接将stream流,返回一个Bitmap对象,
6.ImageView.setImageURI(Uri.fromFile(file)); 给imageview设置图片,Uri.fromFile(file)方法将file对象转换成 uri 对象
ImageView.setImageBitmap(bitmap); imageview 通过bitmap对象,来设置图片
7.conn.setDoOutput(true); 设置http协议可以向服务器写数据
8.获取XML 使用URL封装路径,打开一个HttpURLConnection 设置头信息之后获取相应码,从输入流中获取数据 使用XmlPullPaser解析
9.获取JSON 使用URL封装路径,打开一个HttpURLConnection 设置头信息之后获取相应码,从输入流中获取数据 将数据转为String,封装成JSONArray对象 遍历JSONArray对象,调用获取其中的JSONObject 再从JSONObject中获取每个字段的信息
10.发送GET请求 拼接路径和参数,通过URL进行封装,打开一个HttpURLConnection,发送请求 如果参数是中文会出现乱码 URL中包含的中文参数需要使用URLEncoder进行编码 服务器端如果是TOMCAT,其默认使用ISO8859-1编码,接收时需要处理编码问题
11.发送POST请求 通过URL打开一个HttpURLConnection 头信息中除了超时时间和请求方式之外还必须设置Content-Type和Content-Length 从HttpURLConnection获得输出流输出参数数据 服务端可以使用request对象的setCharacterEncoding方法设置编码
12.httpclient:浏览器的简单包装 new DefaultHttpClient 就相当于得到了一个默认的浏览器
13.通过HttpClient向服务端发送请求 GET 方式 1.获取一个浏览器的实例 HttpClient client = new DefaultHttpClient(); 2.准备请求地址 String param1 = URLEncoder.encode(name); String param2 = URLEncoder.encode(password); HttpGet httpGet = new HttpGet(path+"?name="+param1+"&password="+param2); 3.回车,发送请求 HttpResponse response = client.execute(httpGFet); int code = response.getStatusLine().getStatusCode(); if(code == 200){ InputStream is = response.getEntity().getContent(); getEntity()获取服务端返回的所有的数据实体 }
14.通过HttpClient向服务器发送请求 POST 方式 1.获取一个浏览器的实例 HttpClient client = new DefaultHttpClient(); 2.准备请求的数据类型 HttpPost httppost = new HttpPost(path);
// 键值对
List< NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", name));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
3.设置post请求的数据实体
httppost.setEntity(entity);
4. 发送数据给服务器
HttpResponse ressponse = client.execute(httppost);
int code = ressponse.getStatusLine().getStatusCode();
if(code == 200){
InputStream is =ressponse.getEntity().getContent();
byte result = StreamTool.getBytes(is);
return new String(result);
}
else{
throw new IllegalStateException("服务器状态异常");
}
14.webService 任何服务器提供的 数据 内容 方法 都可以理解为webservice