1 package com.urldemo.test;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.OutputStreamWriter;
7 import java.io.UnsupportedEncodingException;
8 import java.net.HttpURLConnection;
9 import java.net.MalformedURLException;
10 import java.net.ProtocolException;
11 import java.net.URL;
12 import java.net.URLConnection;
13 import java.nio.Buffer;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17
18 import javax.swing.text.html.parser.Entity;
19
20 import org.apache.http.HttpEntity;
21 import org.apache.http.HttpResponse;
22 import org.apache.http.client.ClientProtocolException;
23 import org.apache.http.client.ResponseHandler;
24 import org.apache.http.client.methods.HttpGet;
25 import org.apache.http.impl.client.CloseableHttpClient;
26 import org.apache.http.impl.client.HttpClients;
27 import org.apache.http.util.EntityUtils;
28
29 public class URLUtil {
30 /**
31 *
32 * 1、
33 */
34 public static String SendURLAndParam(String url, String method, String param) {
35 String res = "";
36 BufferedReader reader = null;
37 try {
38 // 1、获取真正的url
39 // url = url+"?";
40 URL realUrl = new URL(url + "?" + param);// 没有param url跟上?也不会出错
41 // 2、获取url链接
42 URLConnection conn = realUrl.openConnection();
43 // 3、设置链接属性
44 // Http报头分为通用报头,请求报头,响应报头和实体报头。
45 conn.setRequestProperty("accept", "*/*");
46 conn.setRequestProperty("Method", method);// GET还是POST
47 conn.setRequestProperty("connection", "Keep-Alive");
48 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 用户代理
49 // 4、建立连接
50 conn.connect();
51 // 5、获取所有响应头字段
52 Map<String, List<String>> map = conn.getHeaderFields();
53 // 6、遍历所有响应头字段,获取到 cooies等
54 for (String key : map.keySet()) {
55 System.out.println(key + "-->" + map.get(key));
56 }
57 // 7、定义BufferedReader 输入流来读取 URL的响应
58 reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
59 String line;// 循环读取
60 while ((line = reader.readLine()) != null) {
61 res += line;
62 }
63 } catch (IOException e) {
64 e.printStackTrace();
65 } finally {
66 if (reader != null) {// 关闭流
67 try {
68 reader.close();
69 } catch (IOException e) {
70 e.printStackTrace();
71 }
72 }
73 }
74 return res;
75 }
76 /**
77 *
78 * 2、
79 * @return
80 */
81 static public String sendHttpURLAndData(String postData, String postUrl) {
82
83 try {
84 URL url = new URL(postUrl);
85 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
86 conn.setRequestMethod("POST");
87 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
88 conn.setRequestProperty("connection", "Keep-Alive");
89 conn.setUseCaches(false);
90 conn.setDoOutput(true);
91
92 conn.setRequestProperty("Content-Length", "" + postData.length());
93 OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
94 out.write(postData);
95 out.flush();
96 out.close();
97
98 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
99 return "";
100 }
101 String line, result = "";
102 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
103 while ((line = in.readLine()) != null) {
104 result += line + "\n";
105 }
106 in.close();
107 return result;
108 } catch (Exception e) {
109 }
110 return "";
111 }
112
113 /**
114 *
115 * 3、使用httpclient进行访问,需要是到 http://hc.apache.org/下载jar包
116 *
117 * @param url
118 * @return
119 */
120 static public String callOnHttp(String url) {
121 String address = "";
122 CloseableHttpClient httpClient = HttpClients.createDefault();
123
124 try {
125 HttpGet httpGet = new HttpGet(url);
126 ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
127
128 @Override
129 public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
130 int status = response.getStatusLine().getStatusCode();
131 if (status >= 200 && status < 300) {
132 HttpEntity entity = response.getEntity();
133 return entity != null ? EntityUtils.toString(entity) : null;
134 } else {
135 throw new ClientProtocolException("Unexpected response status:" + status);
136 }
137
138 }
139 };
140 address = httpClient.execute(httpGet, responseHandler);
141 } catch (Exception e) {
142 e.printStackTrace();
143 } finally {
144 try {
145 httpClient.close();
146 } catch (IOException e) {
147 e.printStackTrace();
148 }
149
150 }
151
152 return address;
153 }
154
155 static public String getWeather(String url, String apiKey, String city) {
156 String param = "key=" + apiKey + "&city=" + city;
157 String result = SendURLAndParam(url, "GET", param);
158 return result;
159 }
160
161 public static void main(String[] args) {
162 String weather = getWeather("http://api.91cha.com/weather", "8c5abe8df3574e23b73aeb51c1efb667", "北京");
163 System.out.println(weather);
164 }
165 }