4月16日 網絡編程2
阿新 • • 發佈:2019-04-17
nec 處理 edi void cit imp nco 我們 build
今日學習的是http編程續
我不是特別懂老師,今天說我昨天學習的內容是老版本的知識了,現在幾乎不使用了,現在有更好的包了,有點頭大。
今天學習的是jdk9才開始自帶的包HttpClient 和apache 的包 HttpComponents
相比較之下我更喜歡HttpComponents包 我感覺這個更簡單易懂一點
但是今日學習還是只是有點懵懂 加油吧
我都只學到了他們的GET 和 POST 獲取http信息 和 輸入數據
相對來說POST 要比 GET難 ,不是特別懂那個&符號
HttpComponents包是第三方包 需要去下載
但是我們在之前學習了maven 可以自動下載
建立一個maven項目 在他的pom.xml文件裏寫入第三方包的依賴文件代碼就可以自動下載了
附今日代碼:
1 import java.io.IOException; 2 3 import org.apache.http.HttpEntity; 4 import org.apache.http.HttpResponse; 5 import org.apache.http.client.ClientProtocolException; 6 import org.apache.http.client.ResponseHandler; 7 import org.apache.http.client.config.RequestConfig;8 import org.apache.http.client.methods.HttpGet; 9 import org.apache.http.impl.client.CloseableHttpClient; 10 import org.apache.http.impl.client.HttpClients; 11 import org.apache.http.util.EntityUtils; 12 13 public class HttpComponentsGetTest { 14 15 public final static void main(String[] args) throwsException { 16 17 CloseableHttpClient httpClient = HttpClients.createDefault(); 18 RequestConfig requestConfig = RequestConfig.custom() 19 .setConnectTimeout(5000) //設置連接超時時間 20 .setConnectionRequestTimeout(5000) // 設置請求超時時間 21 .setSocketTimeout(5000) 22 .setRedirectsEnabled(true)//默認允許自動重定向 23 .build(); 24 //設置需要獲取信息的URL 25 HttpGet httpGet = new HttpGet("http://www.baidu.com"); 26 //將需要獲取信息的配置設置給HttpGet對象 27 httpGet.setConfig(requestConfig); 28 //定義字符串用來存放返回結果 29 String srtResult = ""; 30 try { 31 //將httpClient執行execute方法 將返回的結果給Response 32 HttpResponse httpResponse = httpClient.execute(httpGet); 33 //判斷返回的代碼 200 代表成功 404 代表未找到 500代表服務器問題 34 if(httpResponse.getStatusLine().getStatusCode() == 200){ 35 //將返回結果放入字符串 36 srtResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");//獲得返回的結果 37 System.out.println(srtResult); 38 }else 39 { 40 //異常處理 41 } 42 } catch (IOException e) { 43 e.printStackTrace(); 44 }finally { 45 try { 46 httpClient.close(); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } 50 } 51 } 52 }
1 import java.io.IOException; 2 import java.net.URLEncoder; 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.apache.http.HttpResponse; 7 import org.apache.http.client.config.RequestConfig; 8 import org.apache.http.client.entity.UrlEncodedFormEntity; 9 import org.apache.http.client.methods.HttpPost; 10 import org.apache.http.impl.client.CloseableHttpClient; 11 import org.apache.http.impl.client.HttpClientBuilder; 12 import org.apache.http.impl.client.LaxRedirectStrategy; 13 import org.apache.http.message.BasicNameValuePair; 14 import org.apache.http.util.EntityUtils; 15 16 public class HttpComponentsPostTest { 17 18 public final static void main(String[] args) throws Exception { 19 20 //獲取可關閉的 httpCilent 21 //CloseableHttpClient httpClient = HttpClients.createDefault(); 22 CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); 23 //配置超時時間 24 RequestConfig requestConfig = RequestConfig.custom(). 25 setConnectTimeout(10000).setConnectionRequestTimeout(10000) 26 .setSocketTimeout(10000).setRedirectsEnabled(false).build(); 27 28 HttpPost httpPost = new HttpPost("https://tools.usps.com/go/ZipLookupAction.action"); 29 //設置超時時間 30 httpPost.setConfig(requestConfig); 31 32 //裝配post請求參數 33 List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); 34 list.add(new BasicNameValuePair("tAddress", URLEncoder.encode("1 Market Street", "UTF-8"))); //請求參數 35 list.add(new BasicNameValuePair("tCity", URLEncoder.encode("San Francisco", "UTF-8"))); //請求參數 36 list.add(new BasicNameValuePair("sState", "CA")); //請求參數 37 try { 38 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8"); 39 //設置post求情參數 40 httpPost.setEntity(entity); 41 httpPost.setHeader("User-Agent", "HTTPie/0.9.2"); 42 //httpPost.setHeader("Content-Type","application/form-data"); 43 HttpResponse httpResponse = httpClient.execute(httpPost); 44 String strResult = ""; 45 if(httpResponse != null){ 46 System.out.println(httpResponse.getStatusLine().getStatusCode()); 47 if (httpResponse.getStatusLine().getStatusCode() == 200) { 48 strResult = EntityUtils.toString(httpResponse.getEntity()); 49 } 50 else { 51 strResult = "Error Response: " + httpResponse.getStatusLine().toString(); 52 } 53 }else{ 54 55 } 56 System.out.println(strResult); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 }finally { 60 try { 61 if(httpClient != null){ 62 httpClient.close(); //釋放資源 63 } 64 } catch (IOException e) { 65 e.printStackTrace(); 66 } 67 } 68 } 69 }
1 import java.io.IOException; 2 import java.net.URI; 3 import java.net.URLEncoder; 4 import java.net.http.HttpClient; 5 import java.net.http.HttpRequest; 6 import java.net.http.HttpResponse; 7 import java.nio.charset.Charset; 8 9 public class JDKHttpClientGetTest { 10 11 public static void main(String[] args) throws IOException, InterruptedException { 12 doGet(); 13 } 14 15 public static void doGet() { 16 try{ 17 HttpClient client = HttpClient.newHttpClient(); 18 HttpRequest request = HttpRequest.newBuilder(URI.create("http://www.baidu.com")).build(); 19 HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); 20 System.out.println(response.body()); 21 } 22 catch(Exception e) { 23 e.printStackTrace(); 24 } 25 } 26 }
1 import java.io.IOException; 2 import java.net.URI; 3 import java.net.URLEncoder; 4 import java.net.http.HttpClient; 5 import java.net.http.HttpRequest; 6 import java.net.http.HttpResponse; 7 8 public class JDKHttpClientPostTest { 9 10 public static void main(String[] args) throws IOException, InterruptedException { 11 doPost(); 12 } 13 14 public static void doPost() { 15 try { 16 HttpClient client = HttpClient.newBuilder().build(); 17 HttpRequest request = HttpRequest.newBuilder() 18 .uri(URI.create("https://tools.usps.com/go/ZipLookupAction.action")) 19 //.header("Content-Type","application/x-www-form-urlencoded") 20 .header("User-Agent", "HTTPie/0.9.2") 21 .header("Content-Type","application/x-www-form-urlencoded;charset=utf-8") 22 //.method("POST", HttpRequest.BodyPublishers.ofString("tAddress=1 Market Street&tCity=San Francisco&sState=CA")) 23 //.version(Version.HTTP_1_1) 24 .POST(HttpRequest.BodyPublishers.ofString("tAddress=" 25 + URLEncoder.encode("1 Market Street", "UTF-8") 26 + "&tCity=" + URLEncoder.encode("San Francisco", "UTF-8") + "&sState=CA")) 27 //.POST(HttpRequest.BodyPublishers.ofString("tAddress=" + URLEncoder.encode("1 Market Street", "UTF-8") + "&tCity=" + URLEncoder.encode("San Francisco", "UTF-8") + "&sState=CA")) 28 .build(); 29 HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); 30 System.out.println(response.statusCode()); 31 System.out.println(response.headers()); 32 System.out.println(response.body().toString()); 33 34 } 35 catch(Exception e) { 36 e.printStackTrace(); 37 } 38 } 39 }
4月16日 網絡編程2