Android 网络编程之HttpURLConnection运用

时间:2022-03-01 05:05:29

Android 网络编程之HttpURLConnection

利用HttpURLConnection对象,我们可以从网络中获取网页数据.

01 URL url = new URL("http://www.sohu.com");
02     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
03     conn.setConnectTimeout(61000);//设置连接超时
04     if (conn.getResponseCode() != 200throw new RuntimeException("请求url失败");
05     InputStream is = conn.getInputStream();//得到网络返回的输入流
06     String result = readData(is, "GBK");
07     conn.disconnect();
08     System.out.println(result);
09     //第一个参数为输入流,第二个参数为字符集编码
10     public static String readData(InputStream inSream, String charsetName) throws Exception{
11         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
12         byte[] buffer = new byte[1024];
13         int len = -1;
14         while( (len = inSream.read(buffer)) != -1 ){
15             outStream.write(buffer, 0, len);
16         }
17         byte[] data = outStream.toByteArray();
18         outStream.close();
19         inSream.close();
20         return new String(data, charsetName);
21     }

利用HttpURLConnection对象,我们可以从网络中获取文件数据.

02 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
03 conn.setConnectTimeout(61000);
04 if (conn.getResponseCode() != 200throw new RuntimeException("请求url失败");
05 InputStream is = conn.getInputStream();
06 readAsFile(is, "Img269812337.jpg");
07  
08 public static void readAsFile(InputStream inSream, File file) throws Exception{
09     FileOutputStream outStream = new FileOutputStream(file);
10     byte[] buffer = new byte[1024];
11     int len = -1;
12     while( (len = inSream.read(buffer)) != -1 ){
13         outStream.write(buffer, 0, len);
14     }
15      outStream.close();
16     inSream.close();
17 }

利用HttpURLConnection对象,我们可以向网络发送请求参数.

02 Map<String, String> requestParams = new HashMap<String, String>();
03 requestParams.put("age""12");
04 requestParams.put("name""中国");
05  StringBuilder params = new StringBuilder();
06 for(Map.Entry<String, String> entry : requestParams.entrySet()){
07     params.append(entry.getKey());
08     params.append("=");
09     params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
10     params.append("&");
11 }
12 if (params.length() > 0) params.deleteCharAt(params.length() - 1);
13 byte[] data = params.toString().getBytes();
14 URL realUrl = new URL(requestUrl);
15 HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
16 conn.setDoOutput(true);//发送POST请求必须设置允许输出
17 conn.setUseCaches(false);//不使用Cache
18 conn.setRequestMethod("POST");           
19 conn.setRequestProperty("Connection""Keep-Alive");//维持长连接
20 conn.setRequestProperty("Charset""UTF-8");
21 conn.setRequestProperty("Content-Length", String.valueOf(data.length));
22 conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
23 DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
24 outStream.write(data);
25 outStream.flush();
26 if( conn.getResponseCode() == 200 ){
27         String result = readAsString(conn.getInputStream(), "UTF-8");
28         outStream.close();
29         System.out.println(result);
30 }

利用HttpURLConnection对象,我们可以向网络发送xml数据.

01 StringBuilder xml =  new StringBuilder();
02 xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
03 xml.append("<M1 V=10000>");
04 xml.append("<U I=1 D=\"N73\">中国</U>");
05 xml.append("</M1>");
06 byte[] xmlbyte = xml.toString().getBytes("UTF-8");
08 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
09 conn.setConnectTimeout(61000);
10 conn.setDoOutput(true);//允许输出
11 conn.setUseCaches(false);//不使用Cache
12 conn.setRequestMethod("POST");           
13 conn.setRequestProperty("Connection""Keep-Alive");//维持长连接
14 conn.setRequestProperty("Charset""UTF-8");
15 conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
16 conn.setRequestProperty("Content-Type""text/xml; charset=UTF-8");
17 DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
18 outStream.write(xmlbyte);//发送xml数据
19 outStream.flush();
20 if (conn.getResponseCode() != 200throw new RuntimeException("请求url失败");
21 InputStream is = conn.getInputStream();//获取返回数据
22 String result = readAsString(is, "UTF-8");
23 outStream.close();