专栏首页Nicky's blogHttp接口调用示例教程

Http接口调用示例教程

版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/u014427391/article/details/97398717

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

import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://ocr-api.ccint.com/ocr_service?app_key=%s";
        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 httpClient = HttpClients.createDefault();
    //https://github.com/search?utf8=%E2%9C%93&q=jeeplatform&type=
    URIBuilder uriBuilder = new URIBuilder("https://github.com/search");
    uriBuilder.addParameter("q","jeeplatform");
    HttpGet httpGet = new HttpGet(uriBuilder.build());
    CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if(statusCode==200){
        HttpEntity entity = httpResponse.getEntity();
        System.out.println(EntityUtils.toString(entity,"UTF-8"));
    }
    httpClient.close();
    httpResponse.close();

HttpClient的POST请求,与GET请求类似

    CloseableHttpClient httpClient = HttpClients.createDefault();
    //https://www.sogou.com/sie?query=%E8%8A%B1%E5%8D%83%E9%AA%A8&hdq=AQ7CZ&ekv=3&ie=utf8&
    String uri = "https://www.sogou.com/sie";
    List<NameValuePair> params= new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("query","花千骨"));
    StringEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if(statusCode == 200){
        System.out.println(EntityUtils.toString(httpResponse.getEntity()));
    }
    httpClient.close();
    httpResponse.close();

上面例子是可以支持访问签名要求没那么高的接口,然后访问自签名https的站点,那就要建立一个自定义的SSLContext对象,该对象要有可以存储信任密钥的容器,还要有判断当前连接是否受信任的策略,以及在SSL连接工厂中取消对所有主机名的验证,如果还是使用默认的HttpClient是会有下面的异常:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

给出解决方法:

public static CloseableHttpClient getClient() {
		RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
		ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
		registryBuilder.register("http", 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("https", sslSF);
		} catch (KeyStoreException e) {
			throw new RuntimeException(e);
		} catch (KeyManagementException e) {
			throw new RuntimeException(e);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		Registry<ConnectionSocketFactory> 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 httpClient = getClient()就可以

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

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 图片美化增强AI接口调用手册

    POST BODY,接口要求以Post body方式发送,因为要传base64字符串,请求参数过长有400错误的

    SmileNicky
  • Mybatis3.2扫描ant通配符格式的typeAliasPackage

    业务场景:首先项目进行分布式拆分之后,按照模块再分为为api层和service层,web层。 其中订单业务的实体类放在com.muses.taoshop.it...

    SmileNicky
  • 中间件技术入门教程

    中间件:中间件是一种介于操作系统和应用软件之间的一种软件,它使用系统软件所提供的基础服务(功能),衔接网络上应用系统的各个部分或不同的应用,能够达到资源共享、功...

    SmileNicky
  • Java微信公众平台开发(七)--多媒体消息回复之图片回复

    之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复【普通消息类型消息】,这里将讲述多媒体消息的回复方法,【多媒体消息】包含回复图片消息...

    用户2417870
  • 图片美化增强AI接口调用手册

    POST BODY,接口要求以Post body方式发送,因为要传base64字符串,请求参数过长有400错误的

    SmileNicky
  • Android网络访问Post请求的两种写法

    public String sendPost(String url, String param) { PrintWriter out = null;//网络请求...

    wust小吴
  • 如何在Mac OS上使用UiAutomator快速调试类

    本人最近在Mac OS上使用UiAutomator快速调试类的时候发现跟Windows环境下使用有很大的区别,对于我这个Mac OS小白来说有很多坑要填,今天终...

    八音弦
  • 语音识别 | Java 实现 AI 人工智能技术 - 语音识别功能

    说到语音识别、语音翻译、图像识别、人脸识别等等,现在已经非常非常非常普及了,看过‘最强大脑’的朋友,也应该对‘小度’这个机器人有所了解,战胜国际顶尖的‘大脑’-...

    码神联盟
  • Java企业微信开发_07_JSSDK多图上传

     所有的JS接口只能在企业微信应用的可信域名下调用(包括子域名),可在企业微信的管理后台“我的应用”里设置应用可信域名。这个域名必须要通过ICP备案,不然jss...

    shirayner
  • JavaScript专题之深浅拷贝

    如果是数组,我们可以利用数组的一些方法比如:slice、concat 返回一个新数组的特性来实现拷贝。

    疯狂的技术宅

扫码关注云+社区

领取腾讯云代金券