java连接外部程序的接口_HttpClient实现调用外部项目接口工具类的示例

实例如下:

import java.io.IOException;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.http.NameValuePair;

import org.apache.http.HttpEntity;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.conn.ssl.DefaultHostnameVerifier;

import org.apache.http.conn.util.PublicSuffixMatcher;

import org.apache.http.conn.util.PublicSuffixMatcherLoader;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

public class HttpUtils {

private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)

.setConnectionRequestTimeout(15000).build();

public static String sendHttpGet(HttpGet httpGet) {

CloseableHttpClient httpClient = null;

CloseableHttpResponse response = null;

HttpEntity entity = null;

String responseContent = null;

try {

// 创建默认的httpClient实例.

httpClient = HttpClients.createDefault();

httpGet.setConfig(requestConfig);

// 执行请求

response = httpClient.execute(httpGet);

entity = response.getEntity();

responseContent = EntityUtils.toString(entity,"UTF-8");

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

// 关闭连接,释放资源

if (response != null) {

response.close();

}

if (httpClient != null) {

httpClient.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return responseContent;

}

/**

* 发送 post请求

* @param httpUrl 地址

* @param maps 参数

*/

public static String sendHttpPost(String httpUrl,Map maps) {

HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost

// 创建参数队列

List nameValuePairs = new ArrayList();

for (String key : maps.keySet()) {

nameValuePairs.add(new BasicNameValuePair(key,maps.get(key)));

}

try {

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

} catch (Exception e) {

e.printStackTrace();

}

return sendHttpPost(httpPost);

}

public static String sendHttpPost(HttpPost httpPost) {

CloseableHttpClient httpClient = null;

CloseableHttpResponse response = null;

HttpEntity entity = null;

String responseContent = null;

try {

// 创建默认的httpClient实例.

httpClient = HttpClients.createDefault();

httpPost.setConfig(requestConfig);

// 执行请求

response = httpClient.execute(httpPost);

entity = response.getEntity();

responseContent = EntityUtils.toString(entity,释放资源

if (response != null) {

response.close();

}

if (httpClient != null) {

httpClient.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return responseContent;

}

/**

* 发送Get请求Https

* @param httpPost

* @return

*/

public static String sendHttpsGet(HttpGet httpGet) {

CloseableHttpClient httpClient = null;

CloseableHttpResponse response = null;

HttpEntity entity = null;

String responseContent = null;

try {

// 创建默认的httpClient实例.

PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));

DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);

httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();

httpGet.setConfig(requestConfig);

// 执行请求

response = httpClient.execute(httpGet);

entity = response.getEntity();

responseContent = EntityUtils.toString(entity,"UTF-8");

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

// 关闭连接,释放资源

if (response != null) {

response.close();

}

if (httpClient != null) {

httpClient.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return responseContent;

}

}

以上这篇HttpClient实现调用外部项目接口工具类的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

相关文章

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Java调用外部接口有几种方法: 1. 使用Java的网络编程API,如java.net.URL和java.net.HttpURLConnection类发送HTTP请求。 2. 使用第三方的HTTP客户端库,如Apache HttpClient、OkHttp或者Netty。 3. 使用Java中的反射机制动态加载并调用外部接口。 具体的实现方法可以参考Java相关的文档和教程。 ### 回答2: 在Java中,我们可以使用多种方式来调用外部接口。 1. 使用HTTP请求库:Java中常用的库有Apache HttpClient和OkHttp。我们可以通过这些库发送HTTP请求,调用外部接口。首先,我们需要构建一个URL,指定要调用接口地址和参数。然后,使用库提供的方法发送GET或POST请求,获取返回的结果。 2. 使用Java内置的URL和URLConnection类:Java提供了URL和URLConnection类,可以直接与外部接口进行交互。首先,我们需要创建一个URL对象,指定接口地址。然后,使用openConnection方法打开一个连接。接下来,我们可以设置请求方法、请求头、请求参数等。最后,使用getInputStream或getOutputStream方法获取返回的结果。 3. 使用Java的WebService客户端:如果外部接口是一个Web服务,我们可以使用Java提供的WebService客户端工具来调用。首先,我们需要生成WebService客户端代码,可以使用工具如wsimport或JAX-WS。然后,我们可以使用生成的客户端代码来调用接口的方法。 除了以上的方法,还有其他一些第三方库也可以用来调用外部接口,如Spring RestTemplate和Retrofit,它们提供了更便捷的方式来调用接口。 无论使用哪种方法,我们都需要了解外部接口的请求方式(GET或POST)、参数格式(JSON或XML等)以及接口文档中提供的其他要求。同时,我们需要处理返回结果,如解析返回的JSON或XML数据,将其转换为Java对象进行处理。 总结起来,Java调用外部接口的方法有很多,我们可以根据具体需求选择合适的方式来实现。 ### 回答3: Java可以通过使用Java提供的网络编程API来调用外部接口。具体来说,可以使用Java的URL类和URLConnection类来建立与外部接口连接,并发送请求和接收响应。 首先,通过创建一个URL对象,指定外部接口的URL地址,可以使用该URL对象来打开一个连接。然后,可以将URLConnection对象强制转换为具体的URLConnection的子类,如HttpURLConnection。 接下来,可以通过设置URLConnection的请求方法(如GET或POST)、添加请求头(如设置Content-Type、Authorization等),以及发送请求参数等来定制请求。可以通过getOutputStream()方法向外部接口发送请求参数,并通过getInputStream()方法读取到外部接口的响应。 在发送请求和接收响应之前,需要进行异常处理和连接的打开与关闭操作。可以使用try-catch语句来捕获可能产生的异常,如MalformedURLException、IOException等。在请求结束后,可以通过调用disconnect()方法来断开与外部接口连接。 以下是一个简单的示例代码,演示了如何使用Java调用外部接口: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ExternalAPICall { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); // 外部接口的URL地址 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 打开连接 connection.setRequestMethod("GET"); // 设置请求方法(GET、POST等) int responseCode = connection.getResponseCode(); // 获取响应码 if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuffer response = new StringBuffer(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println(response.toString()); } else { System.out.println("请求失败,响应码:" + responseCode); } connection.disconnect(); // 断开连接 } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码展示了一个简单的GET请求的例子,实际使用时根据外部接口的要求和需求进行相应的定制。通过不同的请求方法和请求参数,可以实现外部接口的交互和数据传输。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值