日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 默认站点!

默认站点

當前位置: 首頁 >

转:java网络编程-HTTP编程

發布時間:2023/12/3 29 豆豆
默认站点 收集整理的這篇文章主要介紹了 转:java网络编程-HTTP编程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉自:

java網絡編程-HTTP編程_Stillsings的博客-CSDN博客HTTP編程Java HTTP編程支持模擬成瀏覽器的方式去訪問網頁URL, Uniform Resource Locator,代表一個資源URLConnection獲取資源連接器根據URL的openConnection()方法獲得URLConnectionconnect方法,建立和資源的聯系通道getInputStream方法,獲取資源的內容示例代碼:Get獲取網頁h...https://blog.csdn.net/Listen_heart/article/details/104448012


【1】HTTP編程

Java HTTP編程

??? 支持模擬成瀏覽器的方式去訪問網頁
??? URL, Uniform Resource Locator,代表一個資源
??? URLConnection
??????? 獲取資源連接器
??????? 根據URL的openConnection()方法獲得URLConnection
??????? connect方法,建立和資源的聯系通道
??????? getInputStream方法,獲取資源的內容

【2】URLConnection

示例代碼1:Get獲取網頁html-使用URLConnection

package com.lihuan.network.demo03;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map;public class URLConnectionGetTest {public static void main(String[] args) {try {String urlName = "http://www.baidu.com";URL url = new URL(urlName);URLConnection connection = url.openConnection();//建立聯系通道connection.connect();//打印http的頭部信息Map<String, List<String>> headers = connection.getHeaderFields();for (Map.Entry<String, List<String>> entry : headers.entrySet()){String key = entry.getKey();for (String value : entry.getValue()){System.out.println(key + ":" + value);}}//輸出將要收到的內容屬性信息System.out.println("-------------");System.out.println("getContentType: " + connection.getContentType());System.out.println("getContentLength: " + connection.getContentLength());System.out.println("getContentEncoding: " + connection.getContentEncoding());System.out.println("getDate: " + connection.getDate());System.out.println("getExpiration: " + connection.getExpiration());System.out.println("getLastModified:" + connection.getLastModified());System.out.println("-------------");BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));// 輸出收到的內容String line = "";while ((line = br.readLine()) != null){System.out.println(line);}br.close();} catch (IOException e) {e.printStackTrace();}} }


實例代碼2: Post提交表單-使用 HttpURLConnection

package com.lihuan.network.demo03;import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.*; import java.util.HashMap; import java.util.Map; import java.util.Scanner;public class URLConnectionPostTest {public static void main(String[] args) throws IOException {String urlString = "https://tools.usps.com/zip-code-lookup.htm?byaddress";Object userAgent = "HTTPie/0.9.2";Object redirects = "1";CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));Map<String, String> params = new HashMap<String, String>();params.put("tAddress", "1 Market Street");params.put("tCity", "san Francisco");params.put("sState", "CA");String result = doPost(new URL(urlString), params,userAgent == null ? null : userAgent.toString(),redirects == null ? -1 : Integer.parseInt(redirects.toString()));System.out.println(result);}public static String doPost(URL url, Map<String, String> nameValuePairs, String userAgent, int redirects) throws IOException {HttpURLConnection connection = (HttpURLConnection) url.openConnection();//設置請求頭if(userAgent != null){connection.setRequestProperty("User-Agent", userAgent);}//設為不自動重定向if(redirects >= 0){connection.setInstanceFollowRedirects(false);}//設置可以使用conn.getOutputStream().printconnection.setDoOutput(true);//輸出請求的參數try (PrintWriter out = new PrintWriter(connection.getOutputStream())){boolean first = true;for (Map.Entry<String, String> pair : nameValuePairs.entrySet()){//參數拼接if(first){first = false;}else{out.print('&');}String name = pair.getKey();String value = pair.getValue();out.print(name);out.print("=");out.print(URLEncoder.encode(value, "UTF-8"));}}String encoding = connection.getContentEncoding();if(encoding == null){encoding = "UTF-8";}if(redirects > 0){int responseCode = connection.getResponseCode();System.out.println("responseCode: " + responseCode);if(responseCode == HttpURLConnection.HTTP_MOVED_PERM|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP|| responseCode == HttpURLConnection.HTTP_SEE_OTHER){String location = connection.getHeaderField("Location");if(location != null){URL base = connection.getURL();connection.disconnect();return doPost(new URL(base, location), nameValuePairs, userAgent, redirects - 1);}}}else if(redirects == 0){throw new IOException("Too many redirects");}//接下來獲取html內容StringBuilder response = new StringBuilder();try (Scanner in = new Scanner(connection.getInputStream(), encoding)){while (in.hasNextLine()){response.append(in.nextLine());response.append("\n");}}catch (IOException e){InputStream err = connection.getErrorStream();if(err == null) throw e;try (Scanner in = new Scanner(err)){response.append(in.nextLine());response.append("\n");}}return response.toString();} }

【3】JDK HttpClient

??? JDK 9新增,JDK10更新,JDK11正式發
??? java.net.http包
??? 取代URLConnection
??? 支持HTTP/1.1和HTTP/2
??? 實現大部分HTTP方法
??? 主要類
??????? HttpClient
??????? HttpRequest
??????? HttpResponse

HttpComponents

??? 是一個集成的Java HTTP工具包
??? 實現所有HTTP方法: get/post/put/delete
??? 支持自動轉向
??? 支持https協議
??? 支持代理服務器等

HttpComponent示例代碼3:Get獲取網頁html

package com.lihuan.network.demo04;import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpComponentGetTest {public static void main(String[] args) {CloseableHttpClient httpClient = HttpClients.createDefault();RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).build();HttpGet httpGet = new HttpGet("http://www.baidu.com");httpGet.setConfig(requestConfig);String strResult = "";try {HttpResponse httpResponse = httpClient.execute(httpGet);if(httpResponse.getStatusLine().getStatusCode() == 200){strResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");System.out.println(strResult);}else{}} catch (IOException e) {e.printStackTrace();}finally {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}} }

HttpComponent實例代碼4:Post提交表單

package com.lihuan.network.demo04;import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List;public class HttpComponentsPostTest {public static void main(String[] args) throws UnsupportedEncodingException {//獲取可關閉的 httpClientCloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();//配置超時時間RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).setRedirectsEnabled(false).build();HttpPost httpPost = new HttpPost("https://tools.usps.com/zip-code-lookup.htm?byaddress");//設置超時時間httpPost.setConfig(requestConfig);List<BasicNameValuePair> list = new ArrayList<>();list.add(new BasicNameValuePair("tAddress", URLEncoder.encode("1 Market Street", "UTF-8")));list.add(new BasicNameValuePair("tCity", URLEncoder.encode("san Francisco", "UTF-8")));list.add(new BasicNameValuePair("sState", "CA"));try {UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");//設置post請求參數httpPost.setEntity(entity);httpPost.setHeader("User-Agent", "HTTPie/0.9.2");HttpResponse httpResponse = httpClient.execute(httpPost);String strResult = "";if(httpResponse != null){System.out.println(httpResponse.getStatusLine().getStatusCode());if(httpResponse.getStatusLine().getStatusCode() == 200){strResult = EntityUtils.toString(httpResponse.getEntity());}else{strResult = "Error Response:" + httpResponse.getStatusLine().toString();}}else{}System.out.println(strResult);} catch (IOException e) {e.printStackTrace();} finally {if(httpClient != null){try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}} }

總結

以上是默认站点為你收集整理的转:java网络编程-HTTP编程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得默认站点網站內容還不錯,歡迎將默认站点推薦給好友。