Java 调用第三方接口方法

一、 通过JDK网络类Java.net.HttpURLConnection

1.java.net包下的原生java api提供的http请求

使用步骤:

1、通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)。

2、设置请求的参数。

3、发送请求。

4、以输入流的形式获取返回内容。

5、关闭输入流。

2.HttpClientUtil工具类

/*** jdk 调用第三方接口* @author hsq*/
public class HttpClientUtil2 {/*** 以post方式调用对方接口方法* @param pathUrl*/public static String doPost(String pathUrl, String data){OutputStreamWriter out = null;BufferedReader br = null;String result = "";try {URL url = new URL(pathUrl);//打开和url之间的连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设定请求的方法为"POST",默认是GET//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。conn.setRequestMethod("POST");//设置30秒连接超时conn.setConnectTimeout(30000);//设置30秒读取超时conn.setReadTimeout(30000);// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;conn.setDoOutput(true);// 设置是否从httpUrlConnection读入,默认情况下是true;conn.setDoInput(true);// Post请求不能使用缓存conn.setUseCaches(false);//设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,conn.connect();/*** 下面的三句代码,就是调用第三方http接口*///获取URLConnection对象对应的输出流//此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");//发送请求参数即数据out.write(data);//flush输出流的缓冲out.flush();/*** 下面的代码相当于,获取调用第三方http接口后返回的结果*///获取URLConnection对象对应的输入流InputStream is = conn.getInputStream();//构造一个字符流缓存br = new BufferedReader(new InputStreamReader(is));String str = "";while ((str = br.readLine()) != null){result += str;}System.out.println(result);//关闭流is.close();//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。conn.disconnect();} catch (Exception e) {e.printStackTrace();}finally {try {if (out != null){out.close();}if (br != null){br.close();}} catch (IOException e) {e.printStackTrace();}}return result;}/*** 以get方式调用对方接口方法* @param pathUrl*/public static String doGet(String pathUrl){BufferedReader br = null;String result = "";try {URL url = new URL(pathUrl);//打开和url之间的连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设定请求的方法为"GET",默认是GET//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。conn.setRequestMethod("GET");//设置30秒连接超时conn.setConnectTimeout(30000);//设置30秒读取超时conn.setReadTimeout(30000);// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;conn.setDoOutput(true);// 设置是否从httpUrlConnection读入,默认情况下是true;conn.setDoInput(true);// Post请求不能使用缓存(get可以不使用)conn.setUseCaches(false);//设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,conn.connect();/*** 下面的代码相当于,获取调用第三方http接口后返回的结果*///获取URLConnection对象对应的输入流InputStream is = conn.getInputStream();//构造一个字符流缓存br = new BufferedReader(new InputStreamReader(is, "UTF-8"));String str = "";while ((str = br.readLine()) != null){result += str;}System.out.println(result);//关闭流is.close();//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。conn.disconnect();} catch (Exception e) {e.printStackTrace();}finally {try {if (br != null){br.close();}} catch (IOException e) {e.printStackTrace();}}return result;}
}

3.第三方api接口

/*** @author hsq*/
@RestController
@RequestMapping("/api")
public class HelloWorld {private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);@GetMapping ("/getHello")public Result getHelloWord(){log.info("进入到api接口.......");return Result.success("hello world api get 接口数据");}@PostMapping("/postHello")public Result postHelloWord(@RequestBody User user){log.info("进入post 方法.....");System.out.println(user.toString());return Result.success("hello world api post接口数据");}
}

4.测试类

 @Testpublic void testJDKApi(){//测试get方法String s = HttpClientUtil2.doGet("http://localhost:9092/api/getHello");System.out.println("get方法:"+s);//测试post方法User user = new User();user.setUname("胡萝卜");user.setRole("普通用户");//把对象转换为json格式String s1 = JsonUtil.toJson(user);String postString = HttpClientUtil2.doPost("http://localhost:9092/api/postHello",s1);System.out.println("post方法:"+postString);}

结果:

二、通过Apache common封装好的HttpClient

1.引入依赖

         <!--HttpClient--><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><!--json--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.28</version></dependency>

2.httpClientUtil

/***httpClient的get请求方式* 使用GetMethod来访问一个URL对应的网页实现步骤:* 1.生成一个HttpClient对象并设置相应的参数;* 2.生成一个GetMethod对象并设置响应的参数;* 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;* 4.处理响应状态码;* 5.若响应正常,处理HTTP响应内容;* 6.释放连接。* @author hsq*/
public class HttpClientUtil {/*** @param url* @param charset* @return*/public static String doGet(String url, String charset){/*** 1.生成HttpClient对象并设置参数*/HttpClient httpClient = new HttpClient();//设置Http连接超时为5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);/*** 2.生成GetMethod对象并设置参数*/GetMethod getMethod = new GetMethod(url);//设置get请求超时为5秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//设置请求重试处理,用的是默认的重试处理:请求三次getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());String response = "";/*** 3.执行HTTP GET 请求*/try {int statusCode = httpClient.executeMethod(getMethod);/*** 4.判断访问的状态码*/if (statusCode != HttpStatus.SC_OK){System.err.println("请求出错:" + getMethod.getStatusLine());}/*** 5.处理HTTP响应内容*///HTTP响应头部信息,这里简单打印Header[] headers = getMethod.getResponseHeaders();for (Header h: headers){System.out.println(h.getName() + "---------------" + h.getValue());}//读取HTTP响应内容,这里简单打印网页内容//读取为字节数组byte[] responseBody = getMethod.getResponseBody();response = new String(responseBody, charset);System.out.println("-----------response:" + response);//读取为InputStream,在网页内容数据量大时候推荐使用//InputStream response = getMethod.getResponseBodyAsStream();} catch (HttpException e) {//发生致命的异常,可能是协议不对或者返回的内容有问题System.out.println("请检查输入的URL!");e.printStackTrace();} catch (IOException e){//发生网络异常System.out.println("发生网络异常!");}finally {/*** 6.释放连接*/getMethod.releaseConnection();}return response;}/*** post请求* @param url* @param json* @return*/public static String doPost(String url, JSONObject json){HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);postMethod.addRequestHeader("accept", "*/*");postMethod.addRequestHeader("connection", "Keep-Alive");//设置json格式传送postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");//必须设置下面这个HeaderpostMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");//添加请求参数//postMethod.addParameter("param", json.getString("param"));StringRequestEntity param = new StringRequestEntity(json.getString("param"));postMethod.setRequestEntity(param);String res = "";try {int code = httpClient.executeMethod(postMethod);if (code == 200){byte[] responseBody = postMethod.getResponseBody();res = new String(responseBody, "UTF-8");//res = postMethod.getResponseBodyAsString();System.out.println(res);}} catch (IOException e) {e.printStackTrace();}return res;}
}

3.第三方api接口

@RestController
@RequestMapping("/api")
public class HelloWorld {private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);@GetMapping ("/getHello")public Result getHelloWord(){log.info("进入到api接口.......");return Result.success("hello world api get 接口数据");}@PostMapping("/postHello")public Result postHelloWord(@RequestBody User user){log.info("进入post 方法.....");System.out.println(user.toString());return Result.success("hello world api post接口数据");}}

4.测试类

     @Testpublic void testApi() {//测试get方法String s = HttpClientUtil.doGet("http://localhost:9092/api/getHello", "UTF-8");System.out.println("get方法:"+s);//测试post方法User user = new User();user.setUname("胡萝卜");user.setRole("普通用户");JSONObject jsonObject = new JSONObject();String s1 = JsonUtil.toJson(user);jsonObject.put("param",s1);String postString = HttpClientUtil.doPost("http://localhost:9092/api/postHello", jsonObject);System.out.println("post方法:"+postString);}

结果:

三、通过Spring的RestTemplate

1.引入依赖

导入springboot的web包

    <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

2.RestTemplate配置类

/*** @author hsq*/
@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory){return new RestTemplate(factory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory(){SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setConnectTimeout(15000);factory.setReadTimeout(5000);return factory;}
}

3.RestTemplate实现类

/*** @author hsq*/
@Component
public class RestTemplateToInterface {@Autowiredprivate RestTemplate restTemplate;/*** 以get方式请求第三方http接口 getForEntity* @param url* @return*/public Result doGetWith1(String url){ResponseEntity<Result> responseEntity = restTemplate.getForEntity(url, Result.class);Result result = responseEntity.getBody();return result;}/*** 以get方式请求第三方http接口 getForObject* 返回值返回的是响应体,省去了我们再去getBody()* @param url* @return*/public Result doGetWith2(String url){Result result  = restTemplate.getForObject(url, Result.class);return result;}/*** 以post方式请求第三方http接口 postForEntity* @param url* @param user* @return*/public String doPostWith1(String url,User user){ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);String body = responseEntity.getBody();return body;}/*** 以post方式请求第三方http接口 postForEntity* 返回值返回的是响应体,省去了我们再去getBody()* @param url* @param user* @return*/public String doPostWith2(String url,User user){String body = restTemplate.postForObject(url, user, String.class);return body;}/*** exchange* @return*/public String doExchange(String url, Integer age, String name){//header参数HttpHeaders headers = new HttpHeaders();String token = "asdfaf2322";headers.add("authorization", token);headers.setContentType(MediaType.APPLICATION_JSON);//放入body中的json参数JSONObject obj = new JSONObject();obj.put("age", age);obj.put("name", name);//组装HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);String body = responseEntity.getBody();return body;}}

4.第三方api接口

/*** @author hsq*/
@RestController
@RequestMapping("/api")
public class HelloWorld {private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);@GetMapping ("/getHello")public Result getHelloWord(){log.info("进入到api接口.......");return Result.success("hello world api get 接口数据");}@PostMapping("/postHello")public Result postHelloWord(@RequestBody User user){log.info("进入post 方法.....");System.out.println(user.toString());return Result.success("hello world api post接口数据");}
}

5.测试类

//注入使用
@Autowired
private RestTemplateToInterface restTemplateToInterface;@Test
public void testSpringBootApi(){Result result= restTemplateToInterface.doGetWith1("http://localhost:9092/api/getHello");System.out.println("get结果:"+result);User user = new User();user.setUname("胡萝卜");user.setRole("普通用户");String s = restTemplateToInterface.doPostWith1("http://localhost:9092/api/postHello", user);System.out.println("post结果:"+s);
}

结果:

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

Java 调用第三方接口方法相关推荐

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

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

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

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

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

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

  4. 【java调用webservice接口方法】

    webservice的 发布一般都是使用WSDL(web service descriptive language)文件的样式来发布的,在WSDL文件里面,包含这个webservice暴露在外面可供使 ...

  5. java调用第三方接口发送手机验证码

    本实例调用互亿无线触发短信接口,采用commons-httpclient-3.1.jar及dom4j-1.6.1.jar俩个jar包实现,可根据个人需求更改调用接口 //接口类型:互亿无线触发短信接口 ...

  6. java调用第三方接口_java调用第三方接口,获取接口返回的数据。

    java接收远程调用的数据,得到的是如上个数的返回内容,我怎么写才能获取到值,现在使用的请求方法如下: public static HttpResult postJsonData(String url ...

  7. Java调用第三方http接口 单点登录 HttpClient

    Java调用第三方http接口的方式 Java调用第三方接口示范 范例: 响应形式: 主逻辑: 访问此地址:http:// { cas }/cas/login?service=http://local ...

  8. Java调用REST接口(get,post请求方法)

    网上的调用方法实例千奇百怪,以下为本人自己整理的Java调用rest接口方法实例,包含get请求和post请求,可创建工具类方便调用,其中get.post请求解决了入出参中文乱码问题. get方式请求 ...

  9. http方式调用第三方接口

    java如何调用对方http接口(II) - 流年煮雪 - 博客园 纯Java api HttpURLConnection Java调用外部接口_CJD的博客-CSDN博客_调用外部接口 纯Java  ...

最新文章

  1. mysql 大量数据 更改索引_Mysql索引数据结构详解与索引优化
  2. 交换机模拟配置软件_网络设备模拟器Packet Tracer实验
  3. SASE — Overview
  4. Android Shape使用
  5. 基于ZYNQ实时目标检测系统
  6. 小米miuiVS华为鸿蒙,华为鸿蒙2.0 vs 小米MIUI 12.5
  7. 【微机原理与接口技术】具体芯片(1)并行接口8255A(1):全局观
  8. wxpython wx listctrl_wxPython - ListCtrl列表排序
  9. NameNode所需配置,NameNode内存配置计算,NameNode与block关系
  10. python list索引遍历_在python中遍历dict和list
  11. 我对于男人喜欢喷香水是觉得很恶心的一件事
  12. 1.1 ubuntu环境下搭建gd32vf103
  13. 条形码的码制分类详解
  14. 自动配置的IPv4地址怎么取消
  15. golang dep安装
  16. 同城跑腿微信小程序制作步骤_分享下同城跑腿小程序的作用
  17. Django源码cookie解读:关于中文cookie会被吞掉并截断的问题。
  18. java成员变量默认是_在Java语言中,String类型的成员变量的默认初始值是( )
  19. android xlog崩溃日志,Android第三方log库:xlog使用记录
  20. x264命令参数与代码中变量的对应关系

热门文章

  1. 25岁给自己做个职业规划吧!
  2. 央行:2018年非银行支付机构发生网络支付业务量同比大涨85.05%...
  3. UESTC 1253 阿里巴巴和n个大盗(博弈)
  4. 在simulink中采用模块搭建了基于双二阶广义积分器的三相锁相环,整个仿真环境完全离散化
  5. 【JAVA】2022年JAVA高级面试题汇总
  6. 详解CommonJS模块与ES6模块
  7. 计算机配件算固定资产吗,计算机和收款机属于固定资产还是低值易耗品?
  8. 霍纳法则--计算多项式的值
  9. $location的解释
  10. log4j学习笔记--ConversionPattern参数详解-- RollingFileAppender选项