4月15日 网络编程

今日学习的是http(超文本传输协议)编程

使用的一般是HTML(超文本标记语言)的格式

说实话今天学的有点脑袋疼,完全的听不懂,老师也说不用在意一些地方,是属于http范畴内的。

协议还有一个https(加密的)

URL(统一资源定位器)

今日所学到的知识大概就只有点概念知识。代码的基本没怎么学到。

但是还是附一下老师打的代码,等以后能看懂了有机会再来看看。

附:

 1 import java.io.*;
 2 import java.net.*;
 3 import java.util.*;
 4 
 5 
 6 public class URLConnectionGetTest
 7 {
 8    public static void main(String[] args)
 9    {
10       try
11       {
12          String urlName = "http://www.baidu.com";
13 
14          URL url = new URL(urlName);
15          URLConnection connection = url.openConnection(); 
16          connection.connect();
17 
18          // 打印http的头部信息
19 
20          Map<String, List<String>> headers = connection.getHeaderFields();
21          for (Map.Entry<String, List<String>> entry : headers.entrySet())
22          {
23             String key = entry.getKey();
24             for (String value : entry.getValue())
25                System.out.println(key + ": " + value);
26          }
27 
28          // 输出将要收到的内容属性信息
29 
30          System.out.println("----------");
31          System.out.println("getContentType: " + connection.getContentType());
32          System.out.println("getContentLength: " + connection.getContentLength());
33          System.out.println("getContentEncoding: " + connection.getContentEncoding());
34          System.out.println("getDate: " + connection.getDate());
35          System.out.println("getExpiration: " + connection.getExpiration());
36          System.out.println("getLastModifed: " + connection.getLastModified());
37          System.out.println("----------");
38 
39          BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
40 
41          // 输出收到的内容
42          String line = "";
43          while((line=br.readLine()) != null)
44          {
45              System.out.println(line);
46          }
47          br.close();
48       }
49       catch (IOException e)
50       {
51          e.printStackTrace();
52       }
53    }
54 }
55    
  1 import java.io.*;
  2 import java.net.*;
  3 import java.nio.file.*;
  4 import java.util.*;
  5 
  6 public class URLConnectionPostTest
  7 {
  8    public static void main(String[] args) throws IOException
  9    {
 10       String urlString = "https://tools.usps.com/go/ZipLookupAction.action";
 11       Object userAgent = "HTTPie/0.9.2";
 12       Object redirects = "1";
 13       CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
 14       
 15       Map<String, String> params = new HashMap<String, String>();
 16       params.put("tAddress", "1 Market Street");  
 17       params.put("tCity", "San Francisco");
 18       params.put("sState", "CA");
 19       String result = doPost(new URL(urlString), params, 
 20          userAgent == null ? null : userAgent.toString(), 
 21          redirects == null ? -1 : Integer.parseInt(redirects.toString()));
 22       System.out.println(result);
 23    }   
 24 
 25    public static String doPost(URL url, Map<String, String> nameValuePairs, String userAgent, int redirects)
 26          throws IOException
 27    {        
 28       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 29       if (userAgent != null)
 30          connection.setRequestProperty("User-Agent", userAgent);
 31       
 32       if (redirects >= 0)
 33          connection.setInstanceFollowRedirects(false);
 34       
 35       connection.setDoOutput(true);
 36       
 37       //输出请求的参数
 38       try (PrintWriter out = new PrintWriter(connection.getOutputStream()))
 39       {
 40          boolean first = true;
 41          for (Map.Entry<String, String> pair : nameValuePairs.entrySet())
 42          {
 43             //参数必须这样拼接 a=1&b=2&c=3
 44             if (first) 
 45             {
 46                 first = false;
 47             }
 48             else
 49             {
 50                 out.print('&');
 51             }
 52             String name = pair.getKey();
 53             String value = pair.getValue();
 54             out.print(name);
 55             out.print('=');
 56             out.print(URLEncoder.encode(value, "UTF-8"));
 57          }
 58       }      
 59       String encoding = connection.getContentEncoding();
 60       if (encoding == null) 
 61       {
 62           encoding = "UTF-8";
 63       }
 64             
 65       if (redirects > 0)
 66       {
 67          int responseCode = connection.getResponseCode();
 68          System.out.println("responseCode: " + responseCode);
 69          if (responseCode == HttpURLConnection.HTTP_MOVED_PERM 
 70                || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
 71                || responseCode == HttpURLConnection.HTTP_SEE_OTHER) 
 72          {
 73             String location = connection.getHeaderField("Location");
 74             if (location != null)
 75             {
 76                URL base = connection.getURL();
 77                connection.disconnect();
 78                return doPost(new URL(base, location), nameValuePairs, userAgent, redirects - 1);
 79             }
 80             
 81          }
 82       }
 83       else if (redirects == 0)
 84       {
 85          throw new IOException("Too many redirects");
 86       }
 87       
 88       //接下来获取html 内容
 89       StringBuilder response = new StringBuilder();
 90       try (Scanner in = new Scanner(connection.getInputStream(), encoding))
 91       {
 92          while (in.hasNextLine())
 93          {
 94             response.append(in.nextLine());
 95             response.append("\n");
 96          }         
 97       }
 98       catch (IOException e)
 99       {
100          InputStream err = connection.getErrorStream();
101          if (err == null) throw e;
102          try (Scanner in = new Scanner(err))
103          {
104             response.append(in.nextLine());
105             response.append("\n");
106          }
107       }
108 
109       return response.toString();
110    }
111 }

猜你喜欢

转载自www.cnblogs.com/sucker/p/10713546.html
今日推荐