学堂 学堂 学堂公众号手机端

要调用HTTPS接口,可以使用Java中的HttpURLConnection或HttpClient

lewis 1年前 (2024-03-22) 阅读数 14 #技术

要调用HTTPS接口,可以使用Java中的HttpURLConnection或HttpClient。 下面是使用HttpURLConnection调用HTTPS接口的示例:

importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.net.HttpURLConnection; importjava.net.URL; publicclassHttpsExample{ publicstaticvoidmain(String[]args)throwsIOException{ //创建URL对象 URLurl=newURL("https://api.example.com/endpoint"); //打开连接 HttpURLConnectionconnection=(HttpURLConnection)url.openConnection(); //设置请求方法为GET connection.setRequestMethod("GET"); //获取响应码 intresponseCode=connection.getResponseCode(); System.out.println("ResponseCode:"+responseCode); //读取响应内容 InputStreaminputStream=connection.getInputStream(); BufferedReaderreader=newBufferedReader(newInputStreamReader(inputStream)); Stringline; StringBuilderresponse=newStringBuilder(); while((line=reader.readLine())!=null){ response.append(line); } reader.close(); //输出响应内容 System.out.println("ResponseBody:"+response.toString()); //关闭连接 connection.disconnect(); } }

如果你想要使用HttpClient调用HTTPS接口,可以使用ApacheHttpClient库。你可以通过Maven或Gradle添加以下依赖项:

Maven:


<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>

Gradle:

implementation'org.apache.httpcomponents:httpclient:4.5.13'

下面是使用HttpClient调用HTTPS接口的示例:

importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.client.HttpClient; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.conn.ssl.NoopHostnameVerifier; importorg.apache.http.conn.ssl.TrustSelfSignedStrategy; importorg.apache.http.impl.client.CloseableHttpClient; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.ssl.SSLContextBuilder; importorg.apache.http.util.EntityUtils; importjava.io.IOException; publicclassHttpsExample{ publicstaticvoidmain(String[]args)throwsIOException{ //创建HttpClient对象 CloseableHttpClienthttpClient=HttpClients.custom() .setSSLContext(SSLContextBuilder.create().loadTrustMaterial(newTrustSelfSignedStrategy()).build()) .setSSLHostnameVerifier(newNoopHostnameVerifier()) .build(); //创建HttpGet请求对象 HttpGethttpGet=newHttpGet("https://api.example.com/endpoint"); //发送请求,获取响应 HttpResponseresponse=httpClient.execute(httpGet); //获取响应内容 HttpEntityentity=response.getEntity(); StringresponseBody=EntityUtils.toString(entity); //输出响应内容 System.out.println("ResponseBody:"+responseBody); //关闭HttpClient httpClient.close(); } }

这是两种常用的调用HTTPS接口的方法,你可以根据自己的需求选择其中一种来实现。

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门