Get方式:
// Get方式请求 02.public static void doGet() throws Exception { 03. String path = "http://203.156.252.170:8008/logins?username=liu&pwd=123456"; 04. // 新建一个URL对象 05. URL url = new URL(path); 06. // 打开一个HttpURLConnection连接 07. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 08. // 设置连接超时时间 09. urlConn.setConnectTimeout(3* 1000); 10. // 开始连接 11. urlConn.connect(); 12. // 判断请求是否成功 13. if (urlConn.getResponseCode() == 200) { 14. // 获取返回的数据 15. byte[] data = readStream(urlConn.getInputStream()); 17. Log.i(TAG_GET, new String(data, "UTF-8")); 18. } else { 19. Log.i(TAG_GET, "Get方式请求失败"); 20. } 21. // 关闭连接 22. urlConn.disconnect(); 23.}
Post方式:
// Post方式请求 02.public static void doPost() throws Throwable { 03. String path = "http://203.156.252.170:8008/logins"; 04. // 请求的参数转换为byte数组 05. String params = "username=" + URLEncoder.encode("liu", "UTF-8") 06. + "&pwd=" + URLEncoder.encode("123456", "UTF-8"); 07. byte[] postData = params.getBytes(); 08. // 新建一个URL对象 09. URL url = new URL(path); 10. // 打开一个HttpURLConnection连接 11. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 12. // 设置连接超时时间 13. urlConn.setConnectTimeout(3 * 1000); 14. // Post请求必须设置允许输出 15. urlConn.setDoOutput(true); 16. // Post请求不能使用缓存 17. urlConn.setUseCaches(false); 18. // 设置为Post请求 19. urlConn.setRequestMethod("POST"); 20. urlConn.setInstanceFollowRedirects(true); 21. // 配置请求Content-Type 22. urlConn.setRequestProperty("Content-Type", 23. "application/x-www-form-urlencode"); 24. // 开始连接 25. urlConn.connect(); 26. // 发送请求参数 27. DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); 28. dos.write(postData); 29. dos.flush(); 30. dos.close(); 31. // 判断请求是否成功 32. if (urlConn.getResponseCode() == 200) { 33. // 获取返回的数据 34. byte[] data = readStream(urlConn.getInputStream()); 35. Log.i(TAG_POST, "Post请求方式成功,返回数据如下:"); 36. Log.i(TAG_POST, new String(data, "UTF-8")); 37. } else { 38. Log.i(TAG_POST, "Post方式请求失败"); 39. } 40.}