1 GET请求
2
3
4 /**
5 * 从网络获取json数据,(String byte[})
6
7 * @param path
8 * @return
9 */
10 public static String getJsonByInternet(String path){
11 try {
12 URL url = new URL(path.trim());
13 //打开连接
14 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
15
16 if(200 == urlConnection.getResponseCode()){
17 //得到输入流
18 InputStream is =urlConnection.getInputStream();
19 ByteArrayOutputStream baos = new ByteArrayOutputStream();
20 byte[] buffer = new byte[1024];
21 int len = 0;
22 while(-1 != (len = is.read(buffer))){
23 baos.write(buffer,0,len);
24 baos.flush();
25 }
26 return baos.toString("utf-8");
27 }
28 } catch (IOException e) {
29 e.printStackTrace();
30 }
31
32 return null;
33 }
34
35
36 POST请求
37
38
39
40 //获取其他页面的数据
41 /**
42 * POST请求获取数据
43 */
44 public static String postDownloadJson(String path,String post){
45 URL url = null;
46 try {
47 url = new URL(path);
48 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
49 httpURLConnection.setRequestMethod("POST");// 提交模式
50 // conn.setConnectTimeout(10000);//连接超时 单位毫秒
51 // conn.setReadTimeout(2000);//读取超时 单位毫秒
52 // 发送POST请求必须设置如下两行
53 httpURLConnection.setDoOutput(true);
54 httpURLConnection.setDoInput(true);
55 // 获取URLConnection对象对应的输出流
56 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
57 // 发送请求参数
58 printWriter.write(post);//post的参数 xx=xx&yy=yy
59 // flush输出流的缓冲
60 printWriter.flush();
61 //开始获取数据
62 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
63 ByteArrayOutputStream bos = new ByteArrayOutputStream();
64 int len;
65 byte[] arr = new byte[1024];
66 while((len=bis.read(arr))!= -1){
67 bos.write(arr,0,len);
68 bos.flush();
69 }
70 bos.close();
71 return bos.toString("utf-8");
72 } catch (Exception e) {
73 e.printStackTrace();
74 }
75 return null;
76 }