Http interface call sample tutorial

Keywords: Java JDK github Windows

Before introducing the use of HttpClient library, first introduce HttpURLConnection in jdk, because HttpClient is an open-source third-party library, which is convenient to use, but it is quite basic in jdk. Sometimes, when there is no HttpClient, HttpURLConnection in jdk can also be used. HttpURLConnection is the jdk java.net library. The following is the example Code:

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"); // Setting Request Mode
            conn.setRequestProperty("Content-Type", "application/json"); // Setting the sending data
            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("Send out POST The request is abnormal!" + 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);
    }
}

Then I will introduce HttpClient, which only gives the example code and does not encapsulate the tool class, because it is easy to encapsulate the tool class itself after understanding the basic usage.

GET Request of HttpClient

   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();

POST requests for HttpClient, similar to GET requests

    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","Hua Qian'gu"));
    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();

The above example can support accessing interfaces with less signature requirements, and then accessing sites with self-signed https. It is necessary to establish a custom SLContext object, which has a container for storing trust keys, a strategy to determine whether the current connection is trusted, and to cancel the verification of all host names in the SSL connection factory, if still silent. The HTTP Client is recognized as having the following exceptions:

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

Solutions are given:

public static CloseableHttpClient getClient() {
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
        ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
        registryBuilder.register("http", plainSF);
        // Specify Trusted Key Storage Objects and Connection Socket Factory
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            // Trust any link
            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();
        // Setting up Connection Manager
        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();
    }

Then Closeable HttpClient httpClient = getClient () will do

Then the HttpClient grammar is relatively complicated? If you find it troublesome, you can use RestTemplate of Spring Framework, where you create a custom bean, create it as needed, code example:

//Essentials for accessing self-signed https
HttpComponentsClientHttpRequestFactory requestFactory = 
                    new HttpComponentsClientHttpRequestFactory(HttpClientUtil.getClient());
         RestTemplate restTemplate = new RestTemplate(requestFactory);*/
         try {
             //Bean result= restTemplate.getForObject(digitalgdOauthUrl, Bean.class);

Posted by yumico23 on Mon, 14 Oct 2019 08:23:25 -0700