HttpClient POST請求第三方接口問題(多參數(shù)傳參)
HttpClient POST請求第三方接口
HttpClient 是Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 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();
//默認(rèn)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ù)
在實(shí)際開發(fā)中,經(jīng)常會碰到需要請求第三方接口的情況,這種接口往往都需要先獲取其身份驗(yàn)證標(biāo)識,以此驗(yàn)證是否有權(quán)限訪問這個接口。
最近我遇到這種情況,需要先獲取到cookie,然后攜帶cookie及參數(shù)一起請求第三方接口,網(wǎng)絡(luò)上有許多方法,這里是根據(jù)我自己的實(shí)際需求編寫的代碼。
依賴
<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ù)雜一點(diǎn),這里又分為兩種,一種為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)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+Vue+Flowable模擬實(shí)現(xiàn)請假審批流程
這篇文章主要為大家詳細(xì)介紹了如何利用SpringBoot+Vue+Flowable模擬實(shí)現(xiàn)一個請假審批流程,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-08-08
java實(shí)現(xiàn)微博后臺登錄發(fā)送微博
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)微博后臺登錄發(fā)送微博的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-07-07

