Http接口调用示例教程

网友投稿 680 2022-11-04

Http接口调用示例教程

Http接口调用示例教程

介绍HttpClient库的使用前,先介绍jdk里HttpURLConnection,因为HttpClient是开源的第三方库,使用方便,不过jdk里的都是比较基本的,有时候没有HttpClient的时候也可以使用jdk里的HttpURLConnection,HttpURLConnection都是调jdk java-库的,下面给出实例代码:

import sun.misc.BASE64Encoder;import java.io.*;import java-.HttpURLConnection;import java-.URL;import java-.URLConnection;public class Main { public static void main(String[] args) throws Exception { String url = " String appKey = "xxxxxx"; // your app_key String appSecret = "xxxxxx"; // your app_secret url = String.format(url, appKey); OutputStreamWriter out = null; BufferedReader in = null; String result = ""; try { String imgData = imageToBase64("example.jpg"); String param="{\"app_secret\":\"%s\",\"image_data\":\"%s\"}"; param=String.format(param,appSecret,imgData); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); // 设置请求方式 conn.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的 conn.connect(); out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.append(param); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } System.out.println(result); } public static String imageToBase64(String path) { String imgFile = path; InputStream in = null; byte[] data = null; try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }}

然后介绍一下HttpClient,只给出实例代码,不封装成工具类,因为理解基本用法后,自己封装工具类也是很容易的

HttpClient的GET请求

CloseableHttpClient = HttpClients.createDefault(); // URIBuilder uriBuilder = new URIBuilder(" uriBuilder.addParameter("q","jeeplatform"); HttpGet = new HttpGet(uriBuilder.build()); CloseableHttpResponse = int statusCode = if(statusCode==200){ HttpEntity entity = System.out.println(EntityUtils.toString(entity,"UTF-8")); } = HttpClients.createDefault(); // String uri = " List params= new ArrayList(); params.add(new BasicNameValuePair("query","花千骨")); StringEntity entity = new UrlEncodedFormEntity(params,"UTF-8"); HttpPost = new HttpPost(uri); CloseableHttpResponse = int statusCode = if(statusCode == 200){ System.out.println(EntityUtils.toString( } path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

给出解决方法:

public static CloseableHttpClient getClient() { RegistryBuilder registryBuilder = RegistryBuilder.create(); ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory(); registryBuilder.register("plainSF); // 指定信任密钥存储对象和连接套接字工厂 try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // 信任任何链接 TrustStrategy anyTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build(); LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registryBuilder.register("sslSF); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } Registry registry = registryBuilder.build(); // 设置连接管理器 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_SECONDS * 1000).setConnectTimeout(TIMEOUT_SECONDS * 1000).build(); return HttpClientBuilder.create().setConnectionManager(connManager).setMaxConnTotal(POOL_SIZE).setMaxConnPerRoute(POOL_SIZE).setDefaultRequestConfig(requestConfig).build(); }

然后CloseableHttpClient = getClient()就可以

然后HttpClient语法相对比较繁杂?如果觉得比较麻烦,可以用Spring框架的RestTemplate,这里要创建一个自定义的bean,根据需要创建,代码示例:

//访问自签名requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientUtil.getClient()); RestTemplate restTemplate = new RestTemplate(requestFactory);*/ Bean result= restTemplate.getForObject(digitalgdOauthUrl, Bean.class);

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:List集合分组实现教程
下一篇:Springboot 如何使用BindingResult校验参数
相关文章

 发表评论

暂时没有评论,来抢沙发吧~