温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java怎么使用HttpClient调用接口

发布时间:2022-10-28 09:27:49 来源:亿速云 阅读:199 作者:iii 栏目:开发技术

这篇文章主要介绍“java怎么使用HttpClient调用接口”,在日常操作中,相信很多人在java怎么使用HttpClient调用接口问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”java怎么使用HttpClient调用接口”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

java使用HttpClient调用接口

HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器

直接言归正传了!!!!上代码

 public static String sendPutForm(String url,  Map<String,String> map, String encoding) throws ParseException, IOException {
        String body = "";
        // 打印了一下我推送的json数据
        log.info("我推送的json数据:" + map);
        log.info("我推送的url:" + url);
        CloseableHttpResponse response = null;
        ///获得Http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
            parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
		// 配置信息
		// 设置连接超时时间(单位毫秒)
		// 设置请求超时时间(单位毫秒)
		// socket读写超时时间(单位毫秒)
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000)
                .setSocketTimeout(50000).build();
        // 向指定资源位置上传内容// 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        httpPost.setEntity(formEntity);
        try {
            response = client.execute(httpPost);
            // 通过response中的getEntity()方法获取返回值
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                body = EntityUtils.toString(entity, encoding);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            httpPost.abort();
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
            }
        }
        log.info("body:" + body);
        return body;
    }

代码其实就是这么多,还有好多形式。大家可以参考写一下。

java的HttpClient调用远程接口

httpClient比jdk自带的URLConection更加易用和方便,这里介绍一下使用httpClient来调用远程接口。

首先导入相关的依赖包:

<!-- httpClient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

使用方法

1,创建HttpClient对象;

2,指定请求URL,并创建请求对象,如果是get请求则创建HttpGet对象,post则创建HttpPost对象;

3,如果请求带有参数,对于get请求可直接在URL中加上参数请求,或者使用setParam(HetpParams params)方法设置参数,对于HttpPost请求,可使用setParam(HetpParams params)方法或者调用setEntity(HttpEntity entity)方法设置参数;

4,调用httpClient的execute(HttpUriRequest request)执行请求,返回结果是一个response对象;

5,通过response的getHeaders(String name)或getAllHeaders()可获得请求头部信息,getEntity()方法获取HttpEntity对象,该对象包装了服务器的响应内容。

实例

我使用了property文件来保存不同API对应的链接,也可以除去properties文件的读取代码,直接将变量 API换成所需URL

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
 
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class APIUtil {
 
	/**
	 * 返回API调用结果
	 * @param APIName 接口在api.properties中的名称
	 * @param params 访问api所需的参数及参数值
	 * @return 此处返回的是JSON格式的数据
	 */
	public static String API(String APIName, Map<String, Object> params) {
		 String content = "";
		 //请求结果  
                CloseableHttpResponse response = null;  
		//实例化httpclient  
                CloseableHttpClient httpclient = HttpClients.createDefault();  
       
            try {
        	 //读取配置文件的URL
                Properties properties = new Properties();
                URL fileURL = APIUtil.class.getClassLoader().getResource("api.properties");
		properties.load(new FileInputStream(new File(fileURL.getFile())));
		String API = properties.getProperty(APIName);
	        //构造url请求
	        StringBuilder url = new StringBuilder(API);
	        if(params!=null && params.size()>0) {
	        	url.append("?");
	        	for(Map.Entry<String, Object> entry : params.entrySet()) {
	            	url.append(entry.getKey()+"="+entry.getValue()+"&");
	            }
	        	url.substring(0, url.length()-1);
	        }
	        //实例化get方法  
	        HttpGet httpget = new HttpGet(url.toString()); 
	        //执行get请求
		response = httpclient.execute(httpget);
		if(response.getStatusLine().getStatusCode()==200) {
			content = EntityUtils.toString(response.getEntity(),"utf-8");
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
        return content;
    }	
}

执行完毕后返回API提供的数据。

到此,关于“java怎么使用HttpClient调用接口”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI