HttpClient POST請求第三方接口問題(多參數(shù)傳參)
HttpClient POST請求第三方接口
HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
在開發(fā)中經(jīng)常遇到和第三方公司接口對接,需要拿到對方提供的數(shù)據(jù)或者是給對方提供,下面給大家提供一個自己寫的demo,本地測試有效,利用post請求傳參訪問 ,希望可以幫到你
package test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSONObject; public class InterfaceRequest { public static void main(String[] args) { String url = "https://www.jianliyisheng.com/api/site/getprovincedata"; HttpClient client = HttpClients.createDefault(); //默認post請求 HttpPost post = new HttpPost(url); //拼接多參數(shù) JSONObject json = new JSONObject(); json.put("uid", "79"); json.put("key", "d86e33fb43036df9f9c29ff8085ac653"); json.put("timestamp", "1562296283"); json.put("typekey", "wshh"); try { post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); System.err.println("狀態(tài):" + httpResponse.getStatusLine()); System.err.println("參數(shù):" + EntityUtils.toString(entity)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
使用httpclient請求第三方接口并攜帶cookie和參數(shù)
在實際開發(fā)中,經(jīng)常會碰到需要請求第三方接口的情況,這種接口往往都需要先獲取其身份驗證標識,以此驗證是否有權(quán)限訪問這個接口。
最近我遇到這種情況,需要先獲取到cookie,然后攜帶cookie及參數(shù)一起請求第三方接口,網(wǎng)絡(luò)上有許多方法,這里是根據(jù)我自己的實際需求編寫的代碼。
依賴
<dependency> ? ? ? <groupId>commons-httpclient</groupId> ? ? ? <artifactId>commons-httpclient</artifactId> ? ? ? <version>3.1</version> </dependency> <dependency> ? ? ?<groupId>org.apache.httpcomponents</groupId> ? ? ?<artifactId>httpmime</artifactId> ? ? ?<version>4.5.10</version> </dependency>
獲取cookie
這里我的情況是每一個小時cookie就會失效,所有后端需要寫一個定時任務(wù)每50分鐘獲取一次cookie,
獲取cooike的方法:
public static String userLogin(String loginUrl, String name, String password) { ? ? ? ? ? ? HttpClient httpClient = new HttpClient(); ? ? ? ? ?? ? ? ? ? ? ? PostMethod postMethod = new PostMethod(loginUrl); ? ? ? ? ? ? ? ? ? ? ? ? NameValuePair[] data = {new NameValuePair("username", name), ? ? ? ? ? ? ? ? ? ? new NameValuePair("password", password)}; ? ? ? ? ? ? postMethod.setRequestBody(data); ? ? ? ? ? ? try { ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); ? ? ? ? ? ? ? ? int statusCode = httpClient.executeMethod(postMethod); ? ? ? ? ? ? ? ? // 獲取 Cookie ? ? ? ? ? ? ? ? Cookie[] cookies = httpClient.getState().getCookies(); ? ? ? ? ? ? ? ? String cookie = null; ? ? ? ? ? ? ? ? for (Cookie c : cookies) { ? ? ? ? ? ? ? ? ? ? //篩選想要的cookie ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? return cookie; ? ? ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? return null; ? ? }
get請求攜帶cookie及參數(shù)
get請求比較簡單易懂,參數(shù)數(shù)據(jù)可以直接添加在請求地址中
?? ?/** ? ? ?* get請求并攜帶cookie ? ? ?* @param url ? ? ?* @return ? ? ?*/ ? ? public static String doGet(String url) { ? ? ? ? try { ? ? ? ? ?? ?//創(chuàng)建get請求 ? ? ? ? ? ? HttpGet httpGet = new HttpGet(url); ? ? ? ? ? ? httpGet.addHeader(new BasicHeader("cookie", UserTask.cookie)); ? ? ? ? ? ? httpGet.setHeader("Connection", "keep-alive"); ? ? ? ? ? ? ? ? ? ? ? ? HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); ? ? ? ? ? ? CloseableHttpClient httpClient = httpClientBuilder.build(); ? ? ? ? ? ? HttpResponse httpResponse = httpClient.execute(httpGet); ? ? ? ? ? ? // 響應(yīng)狀態(tài) ? ? ? ? ? ? if (httpResponse.getStatusLine().getStatusCode() == 200) { ? ? ? ? ? ? ? ? HttpEntity entity = httpResponse.getEntity(); ? ? ? ? ? ? ? ? return EntityUtils.toString(entity, "UTF-8"); ? ? ? ? ? ? } ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? ? ? return “Error”; ? ? }
post請求攜帶cookie及參數(shù)
post請求相對復(fù)雜一點,這里又分為兩種,一種為JSON數(shù)據(jù),一種為表單格式,獲取cookie使用的就是類似表單格式的處理,這里討論的是用的較多的JSON格式,就是第三方接口需要的參數(shù)格式為JSON。
??? ?/** ? ? ?* post請求并攜帶cookie ? ? ?* @param url ? ? ?* @param json ? ? ?* @return ? ? ?*/ ? ? public static String doPostJson(String url, String json) { ? ? ? ? System.out.println(json); ? ? ? ? // 創(chuàng)建Httpclient對象? ? ? ? ? CloseableHttpClient httpClient = HttpClients.createDefault(); ? ? ? ? ? ? ? ? CloseableHttpResponse response = null; ? ? ?? ? ? ? ? try { ? ? ? ? ? ? // 創(chuàng)建Post請求? ? ? ? ? ? ? HttpPost httpPost = new HttpPost(url); ? ? ? ? ? ? httpPost.addHeader(new BasicHeader("cookie", UserTask.cookie)); ? ? ? ? ? ? httpPost.setHeader("Connection", "keep-alive"); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); ? ? ? ? ? ? httpPost.setEntity(entity); ? ? ? ?? ? ? ? ? ? ? response = httpClient.execute(httpPost); ? ? ? ? ? ? if (response.getStatusLine().getStatusCode() == 200) { ? ? ? ? ? ? ? ? return EntityUtils.toString(response.getEntity(), "utf-8"); ? ? ? ? ? ? ?? ? ? ? ? ? ? } ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } finally { ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? response.close(); ? ? ? ? ? ? } catch (IOException e) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return "Error"; ? ? }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA創(chuàng)建Java?Web項目的超詳細圖文教學(xué)
IDEA是程序員們常用的java集成開發(fā)環(huán)境,也是被公認為最好用的java開發(fā)工具,下面這篇文章主要給大家介紹了關(guān)于IDEA創(chuàng)建Java?Web項目的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-12-12IDEA整合Dubbo+Zookeeper+SpringBoot實現(xiàn)
初學(xué)者,想自己動手做一個簡單的demo,本文主要介紹了IDEA整合Dubbo+Zookeeper+SpringBoot實現(xiàn),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-06-06GC調(diào)優(yōu)實戰(zhàn)之高分配速率High?Allocation?Rate
這篇文章主要為大家介紹了GC調(diào)優(yōu)之高分配速率High?Allocation?Rate的實戰(zhàn)示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-01-01idea創(chuàng)建springboot項目(版本只能選擇17和21)的解決方法
idea2023創(chuàng)建spring boot項目時,java版本無法選擇11,本文主要介紹了idea創(chuàng)建springboot項目(版本只能選擇17和21),下面就來介紹一下解決方法,感興趣的可以了解一下2024-01-01Flink實現(xiàn)特定統(tǒng)計的歸約聚合reduce操作
這篇文章主要介紹了Flink實現(xiàn)特定統(tǒng)計的歸約聚合reduce操作,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02Java Socket實現(xiàn)猜數(shù)字小游戲
這篇文章主要為大家詳細介紹了Java Socket實現(xiàn)猜數(shù)字小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09