4以前的版本多用httpclient.getparam方法获取cookie,相对比较简便,4以后的版本,方法各异,但我这里使用的是
HttpClients.custom().setDefaultCookieStore
第一部分获取cookies
第二部分通过cookies登录第三方接口获取数据,并存入数据库。
这就完成了。
下面再附带一个无需cookie请求接口数据的代码。
这里面需要自己封装工具类httpclientUtil,以及自定义方法。
/** javaPublic 自定义工具方法体 * **/ public static JSONObject doPostJson(String url, JSONObject json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; //String resultString = ""; JSONObject result = new JSONObject(); try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); String jsonString= EntityUtils.toString(response.getEntity(), "utf-8"); try { result = JSONObject.parseObject(jsonString); }catch (Exception e){ result = JSONObject.parseObject( "{\"data\":"+jsonString+"}" ); } } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; }