HttpClient POST请求第三方接口问题(多参数传参)
作者:郭优秀的笔记
这篇文章主要介绍了HttpClient POST请求第三方接口问题(多参数传参),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
HttpClient POST请求第三方接口
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
在开发中经常遇到和第三方公司接口对接,需要拿到对方提供的数据或者是给对方提供,下面给大家提供一个自己写的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); //拼接多参数 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("状态:" + httpResponse.getStatusLine()); System.err.println("参数:" + EntityUtils.toString(entity)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
使用httpclient请求第三方接口并携带cookie和参数
在实际开发中,经常会碰到需要请求第三方接口的情况,这种接口往往都需要先获取其身份验证标识,以此验证是否有权限访问这个接口。
最近我遇到这种情况,需要先获取到cookie,然后携带cookie及参数一起请求第三方接口,网络上有许多方法,这里是根据我自己的实际需求编写的代码。
依赖
<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就会失效,所有后端需要写一个定时任务每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及参数
get请求比较简单易懂,参数数据可以直接添加在请求地址中
/** * get请求并携带cookie * @param url * @return */ public static String doGet(String url) { try { //创建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); // 响应状态 if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } return “Error”; }
post请求携带cookie及参数
post请求相对复杂一点,这里又分为两种,一种为JSON数据,一种为表单格式,获取cookie使用的就是类似表单格式的处理,这里讨论的是用的较多的JSON格式,就是第三方接口需要的参数格式为JSON。
/** * post请求并携带cookie * @param url * @param json * @return */ public static String doPostJson(String url, String json) { System.out.println(json); // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { // 创建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"; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。