Gte方法
以上是一些部分代码,测试的时候在测试类中运行对应的测试方法即可。完整代码点点击打开链接下载
public static void requestByGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// 开始连接
urlConn.connect();
// 判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 获取返回的数据
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");
Log.i(TAG_GET, new String(data, "UTF-8"));
} else {
Log.i(TAG_GET, "Get方式请求失败");
}
// 关闭连接
urlConn.disconnect();
}
Post
// Post方式请求
2.public static void requestByPost() throws Throwable {
3. String path = "https://reg.163.com/logins.jsp";
4. // 请求的参数转换为byte数组
5. String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
6. + "&pwd=" + URLEncoder.encode("android", "UTF-8");
7. byte[] postData = params.getBytes();
8. // 新建一个URL对象
9. URL url = new URL(path);
10. // 打开一个HttpURLConnection连接
11. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
12. // 设置连接超时时间
13. urlConn.setConnectTimeout(5 * 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() == HTTP_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.}
以上是一些部分代码,测试的时候在测试类中运行对应的测试方法即可。完整代码点点击打开链接下载