6月份加入fw做开发,接到了个需求,要使用http工具类调用第三方接口,在网上也找了很多http工具类,但是都不满足我的需求:要么是只传递url和一个参数,要么是传递url和一个map集合;

我想要的是传递多个参数,并且参数是JSON格式的,于是我改写了其中的代码,最终完成需求:

package com.engine.qnmd.utils;import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;/*** HttpConnection工具类*/
public class HttpUtil {public static void main(String[] args) throws Exception {//获取tokenString token = Token.getToken();//测试代码JSONObject paramJson2 = new JSONObject();paramJson2.put("code", "1234");paramJson2.put("statuz", "1");String url2="http://";String result = doPost(url2, paramJson2, token);System.out.println(result);}private static Logger log = LoggerFactory.getLogger(HttpUtil.class);/*** post 请求(用于 key-value 格式的参数)* @param url* @param params* @return*/public static String doPost(String url, Map params){BufferedReader in = null;try {// 定义 HttpClientHttpClient client = new DefaultHttpClient();// 实例化 HTTP 方法HttpPost request = new HttpPost();request.setURI(new URI(url));//设置参数List<NameValuePair> nvps = new ArrayList<NameValuePair>();for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {String name = (String) iter.next();String value = String.valueOf(params.get(name));nvps.add(new BasicNameValuePair(name, value));//System.out.println(name +"-"+value);}request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));HttpResponse response = client.execute(request);int code = response.getStatusLine().getStatusCode();if(code == 200){ //请求成功in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"utf-8"));StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = in.readLine()) != null) {sb.append(line + NL);}in.close();return sb.toString();}else{ //log.info("接口调用code:"+code);return null;}}catch(Exception e){e.printStackTrace();return null;}}/*** post 请求(用于请求 json 格式的参数)* @param url* @param json* @return*/public static String doPost(String url, JSONObject json, String token) throws Exception {CloseableHttpClient httpclient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);// 创建 httpPosthttpPost.setHeader("Content-Type", "application/json;charset=utf-8");httpPost.addHeader("Authorization", "Bearer "+token);String charSet = "UTF-8";StringEntity entity = new StringEntity(json.toString(), charSet);httpPost.setEntity(entity);CloseableHttpResponse response = null;try {response = httpclient.execute(httpPost);StatusLine status = response.getStatusLine();int state = status.getStatusCode();log.info("接口调用state:"+state);System.out.println("接口调用state:"+state);if (state == HttpStatus.SC_OK) {HttpEntity responseEntity = response.getEntity();String jsonString = EntityUtils.toString(responseEntity,"UTF-8");return jsonString;}else{return null;}}finally {if (response != null) {try {response.close();} catch (IOException e) {e.printStackTrace();}}try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}}public static String doGet(String url) throws Exception {URL localURL = new URL(url);URLConnection connection = localURL.openConnection();HttpURLConnection httpURLConnection = (HttpURLConnection) connection;httpURLConnection.setRequestMethod("GET");httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");httpURLConnection.setRequestProperty("Content-Type", "x-www-form-urlencoded");InputStream inputStream = null;InputStreamReader inputStreamReader = null;BufferedReader reader = null;StringBuffer resultBuffer = new StringBuffer();String tempLine = null;if (httpURLConnection.getResponseCode() >= 300) {throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());}try {inputStream = httpURLConnection.getInputStream();inputStreamReader = new InputStreamReader(inputStream,"utf-8");reader = new BufferedReader(inputStreamReader);while ((tempLine = reader.readLine()) != null) {resultBuffer.append(tempLine);}} finally {if (reader != null) {reader.close();}if (inputStreamReader != null) {inputStreamReader.close();}if (inputStream != null) {inputStream.close();}}return resultBuffer.toString();}}

我的需求中要用到token,所以我将获取token抽取成一个类,调用方法就可以,大家在使用的过程中,根据要传递的参数的不同可以对方法进行改写,来满足自己的需求。

这是进入公司拿到的第一个需求,继续加油~

http工具类,调用第三方接口相关推荐

  1. WebService工具类调用远程接口服务时java.io.IOException: Server returned HTTP response code: 500 for URL XXX

    问题描述:在本地测试时,使用个人封装的Webservice代码工具类调用远程接口服务时,一切正常.但是一旦将该代码放到一个已有项目的中使用时,就会出现如下所示的错误提示 java.io.IOExcep ...

  2. 如何调用封装工具类调用网上接口查询工作日

    如何调用封装工具类调用网上接口查询工作日 这里的编辑器是STS,用的springboot集成环境: 先引进pom.xml依赖包 <?xml version="1.0" enc ...

  3. Java 调用第三方接口,实战来了!

    在项目开发中经常会遇到调用第三方接口的情况,比如说调用第三方的天气预报接口. 1.准备工作: 在项目的工具包下导入HttpClientUtil这个工具类,或者也可以使用Spring框架的restTem ...

  4. Http调用第三方接口的两种方式实例《超详细!!!》***

    Http调用第三方接口的两种方式<超详细!!!>* 最近在公司做一些调用第三方接口的工作,查阅了一部分的资料和向前辈以及朋友请教,完成了第三方接口的调用,其实主要是通过第三方提供的文档,完 ...

  5. Java调用第三方接口示范

    在项目开发中经常会遇到调用第三方接口的情况,比如说调用第三方的天气预报接口. 使用流程 [1]准备工作:在项目的工具包下导入HttpClientUtil这个工具类,或者也可以使用Spring框架的re ...

  6. Java 调用第三方接口方法

    Java 调用第三方接口方法 一. 通过JDK网络类Java.net.HttpURLConnection 1.java.net包下的原生java api提供的http请求 使用步骤: 1.通过统一资源 ...

  7. java调用第三方接口示例

    引言:在我们开发的过程中,常常会听到或者接触到第三方接口,那么这个第三方接口到底是什么呢? 简单来说就是一个远程接口,不是在你本机上的,你需要通过远程url去访问调用该接口.许多项目中有明确的要求需要 ...

  8. SpringBoot(32) 整合Forest实现调用第三方接口

    一.前言 Forest是什么? Forest是一个高层的.极简的轻量级 HTTP调用API框架,让Java发送HTTP/HTTPS请求不再难.它比OkHttp和HttpClient更高层,比Feign ...

  9. Http请求调用第三方接口

    1.http的post请求调用第三方接口 注意拼接http请求的两点要素:请求头.请求体 1.1 基本调用第三方接口的http请求 //1,获取httpClient对象 CloseableHttpCl ...

最新文章

  1. 解决AttributeError: module ‘tensorflow_core._api.v2.config‘ has no attribute ‘experimental_list_device
  2. 中国人民大学2016考研复试基本分数线
  3. 能打开java文件_用java打开一个本地文件
  4. 如何将字符数组里的内容转换成uint8的类型?将一个字符数组里面的所有元素变成一个字符串?
  5. 2019年计算机一级考试pdf,2019年计算机一级考试试题与答案.pdf
  6. nginx 静态文件缓存
  7. 重要接口—RandomAccess接口
  8. 我不信奉Scrum,我信奉敏捷
  9. phpcmsV9视频模块开发——盛大游戏通行证注册与密码找回
  10. Python--给数字前固定位数加零
  11. TorchSeg—基于PyTorch的快速模块化语义分割开源库
  12. Linux 关于Transparent Hugepages的介绍
  13. 使用web3和infura开发以太坊ethereum区块链
  14. 统计信号处理知识点总结_统计信号处理-简单看看克拉美罗界
  15. 绕过IceSword文件检测的Trojan.Win32.Mnless.zpc/ojj6erv.sys
  16. 企业会计准则第34号——每股收益(2006)
  17. “责任”也是一种竞争力:《穹顶之下》与美丽中国
  18. 境外IP判断一种实现方案
  19. Cortex-M3/M4芯片启动流程概括
  20. 【龙芯1B】:74HC595数码管或74HC138数码管程序开发

热门文章

  1. android Expiring Daemon because JVM Tenured space is exhausted
  2. (附源码)Springboot + vue远程心电诊断系统 毕业设计091759
  3. 网页在苹果Safari浏览器桌面图标
  4. 企业微信如何使用文件盘上传下载查看文件?
  5. 云计算能为运维带来什么?
  6. splunk 中limits.conf 作用
  7. Springboot 配置H2数据库
  8. mysql 语句详解_MySQL 语句详解
  9. Spring Security Oauth2 在资源服务器如何获取jwt中的额外信息
  10. 【网络服务数据库教程】05 Web服务器 - Apache