這篇文章主要介紹“java怎么使用HttpClient調用接口”,在日常操作中,相信很多人在java怎么使用HttpClient調用接口問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”java怎么使用HttpClient調用接口”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
(1)實現了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)
(2)支持自動轉向
(3)支持 HTTPS 協議
(4)支持代理服務器等
public static String sendPutForm(String url, Map<String,String> map, String encoding) throws ParseException, IOException { String body = ""; // 打印了一下我推送的json數據 log.info("我推送的json數據:" + map); log.info("我推送的url:" + url); CloseableHttpResponse response = null; ///獲得Http客戶端 CloseableHttpClient client = HttpClients.createDefault(); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue()); parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); // 配置信息 // 設置連接超時時間(單位毫秒) // 設置請求超時時間(單位毫秒) // socket讀寫超時時間(單位毫秒) RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(50000).setConnectionRequestTimeout(50000) .setSocketTimeout(50000).build(); // 向指定資源位置上傳內容// 創建Post請求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setEntity(formEntity); try { response = client.execute(httpPost); // 通過response中的getEntity()方法獲取返回值 HttpEntity entity = response.getEntity(); if (entity != null) { body = EntityUtils.toString(entity, encoding); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { httpPost.abort(); if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } } log.info("body:" + body); return body; }
代碼其實就是這么多,還有好多形式。大家可以參考寫一下。
httpClient比jdk自帶的URLConection更加易用和方便,這里介紹一下使用httpClient來調用遠程接口。
首先導入相關的依賴包:
<!-- httpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
1,創建HttpClient對象;
2,指定請求URL,并創建請求對象,如果是get請求則創建HttpGet對象,post則創建HttpPost對象;
3,如果請求帶有參數,對于get請求可直接在URL中加上參數請求,或者使用setParam(HetpParams params)方法設置參數,對于HttpPost請求,可使用setParam(HetpParams params)方法或者調用setEntity(HttpEntity entity)方法設置參數;
4,調用httpClient的execute(HttpUriRequest request)執行請求,返回結果是一個response對象;
5,通過response的getHeaders(String name)或getAllHeaders()可獲得請求頭部信息,getEntity()方法獲取HttpEntity對象,該對象包裝了服務器的響應內容。
我使用了property文件來保存不同API對應的鏈接,也可以除去properties文件的讀取代碼,直接將變量 API換成所需URL
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Map; import java.util.Properties; import org.apache.http.client.methods.CloseableHttpResponse; 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; public class APIUtil { /** * 返回API調用結果 * @param APIName 接口在api.properties中的名稱 * @param params 訪問api所需的參數及參數值 * @return 此處返回的是JSON格式的數據 */ public static String API(String APIName, Map<String, Object> params) { String content = ""; //請求結果 CloseableHttpResponse response = null; //實例化httpclient CloseableHttpClient httpclient = HttpClients.createDefault(); try { //讀取配置文件的URL Properties properties = new Properties(); URL fileURL = APIUtil.class.getClassLoader().getResource("api.properties"); properties.load(new FileInputStream(new File(fileURL.getFile()))); String API = properties.getProperty(APIName); //構造url請求 StringBuilder url = new StringBuilder(API); if(params!=null && params.size()>0) { url.append("?"); for(Map.Entry<String, Object> entry : params.entrySet()) { url.append(entry.getKey()+"="+entry.getValue()+"&"); } url.substring(0, url.length()-1); } //實例化get方法 HttpGet httpget = new HttpGet(url.toString()); //執行get請求 response = httpclient.execute(httpget); if(response.getStatusLine().getStatusCode()==200) { content = EntityUtils.toString(response.getEntity(),"utf-8"); } } catch (IOException e) { e.printStackTrace(); } return content; } }
執行完畢后返回API提供的數據。
到此,關于“java怎么使用HttpClient調用接口”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。