HttpClient POST/GET方法


前言:

網絡API接口:https://api.apiopen.top/searchMusic

此API接口返回類型為JSON格式類型

GET:從指定資源請求數據

POST:向指定資源提交要被處理的數據

GET與POST的區別:

①GET在瀏覽器回退時是無害的,而POST會再次提交請求。

②GET只支持URL編碼。

③GET參數通過URL傳遞,參數直接暴露在URL中會泄露信息,POST通過Request body傳遞不會有這樣的問題。

④GET請求在URL中傳遞參數有長度限制,POST沒有長度限制。

⑤對POST請求會險發送Header,服務器相應成功,在發送Date,服務器再次響應,需響應兩次。GET會把Header與Date一起發送到服務端,服務器只響應一次。

一、POST方法

創建POST方法類

 1 package com.HttpClient.Test;
 2 
 3 import java.io.IOException;
 4 import java.util.ArrayList;
 5 
 6 import org.apache.http.HttpEntity;
 7 import org.apache.http.HttpHost;
 8 import org.apache.http.NameValuePair;
 9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.config.RequestConfig;
11 import org.apache.http.client.entity.UrlEncodedFormEntity;
12 import org.apache.http.client.methods.CloseableHttpResponse;
13 import org.apache.http.client.methods.HttpPost;
14 import org.apache.http.impl.client.CloseableHttpClient;
15 import org.apache.http.impl.client.HttpClientBuilder;
16 import org.apache.http.util.EntityUtils;
17 
18 import com.HttpClient.jiexi.HttpClient_jiexi;
19 
20 public class HttpClient_post {
21     
22     private String entityStr;
23     HttpClient_jiexi JSONTOOL = new HttpClient_jiexi();
24     
25     //封裝POST方法
26     public String post(String POST_URL,ArrayList<NameValuePair> list) {
27         
28         try {
29             //把參數放入請求體中
30             UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
31             CloseableHttpClient httpClient = HttpClientBuilder.create().build();
32             HttpPost httpPost = new HttpPost(POST_URL);
33             httpPost.setEntity(entityParam);
34             //發起請求
35             CloseableHttpResponse response = httpClient.execute(httpPost);
36             //獲取返回狀態,並判斷是否連接成功。
37             if (response.getStatusLine().getStatusCode()==200) {
38                 System.out.println("連接成功");
39             } else {
40                 System.out.println("連接異常");
41             }
42             // 獲得響應的實體對象
43             HttpEntity entity = response.getEntity();
44             
45             //轉換成字符串
46             entityStr = EntityUtils.toString(entity, "UTF-8");
47             //關閉請求
48             httpClient.close();
49             
50         } catch (ClientProtocolException e) {
51             System.err.println("Http協議異常");
52             e.printStackTrace();
53         } catch (IOException e) {
54             System.err.println("IO異常");
55             e.printStackTrace();
56         }
57         return entityStr;
58     }
59 
60 }

調用POST方法類

 1 package com.HttpClient.Test;
 2 
 3 import java.util.ArrayList;
 4 import org.apache.http.NameValuePair;
 5 import org.apache.http.message.BasicNameValuePair;
 6 import org.json.JSONException;
 7 import org.testng.annotations.Test;
 8 
 9 public class HttpClient_case1 {
10     
11     HttpClient_post post = new HttpClient_post();
12     private String POST_URL = "https://api.apiopen.top/searchMusic";
13     private String entity;
14     private ArrayList<NameValuePair> list;
15     
16     @Test
17     public void test1() {   
18             // 構造list集合,並添加參數
19             BasicNameValuePair basicNameValuePair = new BasicNameValuePair("name", "十年");
20             list = new ArrayList<>();
21             list.add(basicNameValuePair);
22             // 執行請求,需要傳入URL與參數
23             entity = post.post(POST_URL,list);
24             System.out.println(entity);
25     }
26 
27 }

二、GET方法

創建GET方法類

package com.HttpClient.Test;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient_get {
    
    public String entityStr ;
    public CloseableHttpResponse response ;

    
    public String get(String GET_URL,ArrayList<NameValuePair> list) throws URISyntaxException{try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(GET_URL);
            uriBuilder.setParameters(list);
            //根據帶參數的URI對象構建GET請求對象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            //執行請求
            response = httpClient.execute(httpGet);
            //獲得響應的實體對象
            HttpEntity entity = response.getEntity();
            //轉換成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");

            //關閉請求
            httpClient.close();
        } catch (ClientProtocolException e) {
            System.err.println("Http協議異常");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO異常");
            e.printStackTrace();
        }
        return entityStr;
        
    }

}

調用GET方法類

package com.HttpClient.Test;

import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.testng.annotations.Test;

public class HttpClient_case1 {
    
    HttpClient_get get = new HttpClient_get();
    private String URL = "https://api.apiopen.top/searchMusic";
    private String entity;
    private ArrayList<NameValuePair> list;
    
    @Test
    public void test1() throws URISyntaxException {   
            // 構造list集合
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair("name", "十年");
            list = new ArrayList<>();
            list.add(basicNameValuePair);
            // 執行請求,需要傳入URL與參數
            entity = get.get(URL, list);
            System.out.println(entity);
            
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM