访问URL

三种访问url的方式

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