前言
网络中的URL(Uniform Resource Locator)是统一资源定位符的简称。它表示Internet上某一资源的地址。通过URL我们可以访问Internet上的各种网络资源,比如最常见的WWW,FTP站点。 URL可以被认为是指向互联网资源的“指针”,通过URL可以获得互联网资源相关信息,包括获得URL的InputStream对象获取资源的信息,以及一个到URL所引用远程对象的连接URLConnection。 URLConnection对象可以向所代表的URL发送请求和读取URL的资源。
原理
通常,创建一个URL的连接,需要如下几个步骤:
1.创建URL对象,并通过调用openConnection方法获得URLConnection对象;
2.设置URLConnection参数和普通请求属性;
3.远程资源发送请求;
4.远程资源变为可用,程序可以访问远程资源的头字段和通过输入流来读取远程资源返回的信息。
这里需要重点讨论一下第三步:如果只是发送GET方式请求,使用connect方法建立和远程资源的连接即可;如果是需要发送POST方式的请求,则需要获取URLConnection对象所对应的输出流来发送请求,本文只讨论get方式。这里需要注意的是,由于GET方法的参数传递方式是将参数显式追加在地址后面,那么在构造URL对象时的参数就应当是包含了参数的完整URL地址,而在获得了URLConnection对象之后,就直接调用connect方法即可发送请求。
实现逻辑
1.创建URL对象
2.从URL对象中获取URLConnection对象
3.设置URLConnection请求方法为get
4.连接URLConnection
5.从URLConnection中获取InputStream对象
6.建立InputStreamReader对象从InputStream对象中读取数据
7.建立BufferReader对象从InputStreamReader中对数据进行缓存
8.从BufferedReader中取出数据
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;
* Created by XuDing on 2015/12/3 23:15 上午10:13. */ public class HttpURLDemo { private static final String httpURL ="https://www.baidu.com";
public static void main(String[] args) { System.out.println(request(httpURL)); } * @param httpURL :请求接口 * @return 返回结果 */ public static String request(String httpURL) { StringBuilder stringBuilder = new StringBuilder(); try { URL url = new URL(httpURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String tempString; while ((tempString=bufferedReader.readLine()) != null) { stringBuilder.append(tempString); stringBuilder.append("\r\n"); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); }
return stringBuilder.toString(); } }
|
(本文系作者原创,转载请注明出处)