[Java] Java call third-party interfaces

Get request Http request

https://www.w3school.com.cn/tags/html_ref_httpmethods.asp

HttpClient

  HTTP protocol is probably the most used on the Internet now, the most important agreement, and an increasing number of Java applications need to directly access network resources via the HTTP protocol. Although already it provides the basic functionality to access the HTTP protocol in the JDK java net package, but for most applications, JDK functionality provided by the library itself is not enough rich and flexible. HttpClient is a subproject of Apache Jakarta Common, to provide efficient, new, feature-rich client support HTTP protocol programming toolkit, and it supports the latest version of the HTTP protocol and recommendations.

        A bit like HTTP and the browser, but not the browser. Many people feel that since HttpClient is an HTTP client programming tools, many people regard him as a browser to understand, but in fact HttpClient not the browser, it is a HTTP communication library, so it only provides a general-purpose browser application desired subset of functions, the most fundamental difference is that HttpClient no user interface, the browser needs a rendering engine to display the page, and interprets user input, such as mouse clicks displayed somewhere on the page, there is a layout engine, how to calculate display HTML pages including cascading style sheets and images. javascript interpreter to run embedded HTML page from the HTML page or reference javascript code. Events from the user interface is transmitted to a javascript interpreter for processing. In addition, there are interfaces for plug-ins that can handle Applet, embedded media objects (such as pdf files, Quicktime movies, and Flash animations) or ActiveX control (you can do anything). HttpClient only for transmitting and receiving HTTP messages programmatically through its API.

HttpClient main functions:

Implements all HTTP methods (GET, POST, PUT, HEAD, DELETE, HEAD, OPTIONS, etc.)

  • Support for HTTPS protocol
  • Support proxy server (Nginx, etc.), etc.
  • Supports automatic (jump) steering
  • ……
package cc.mrbird.febs.common.utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    /**
     * 带参数的get请求
     * @param url
     * @param param
     * @return String
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            //Create http GET request 
            HttpGet HttpGet = new new HttpGet (URI);
             // execution request 
            Response = (HttpGet) httpclient.execute;
             // determines whether the state is returned 200 is 
            IF (response.getStatusLine () getStatusCode () == 200 is. {) 
                ResultString = EntityUtils.toString (response.getEntity (), "UTF-. 8" ); 
            } 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } the finally {
             the try {
                 IF ! (Response = null ) {
                    response.close (); 
                } 
                httpclient.close (); 
            } the catch (IOException E) { 
                e.printStackTrace (); 
            } 
        } 
        return ResultString; 
    } 

    / ** 
     * GET request without parameters 
     * @param URL 
     * @return String
      * / 
    public  static String the doGet (String URL) {
         return the doGet (URL, null ); 
    } 

    / ** 
     * POST request with parameters 
     * @param URL
     * @Param param 
     * @return String
      * / 
    public  static String the doPost (String URL, the Map <String, String> param) {
         // create objects Httpclient 
        CloseableHttpClient httpClient = HttpClients.createDefault (); 
        CloseableHttpResponse Response = null ; 
        String ResultString = " " ;
         the try {
             // create Http Post request 
            HttpPost HttpPost = new new HttpPost (url);
             // create a parameter list 
            IF (param =! null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 不带参数的post请求
     * @param url
     * @return String
     */
    public static String doPost(String url) {
        return doPost(url, null); 
    } 

    / ** 
     * type transmission json post request 
     * @param URL 
     * @param json 
     * @return String
      * / 
    public  static String doPostJson (URL String, String json) {
         // create objects Httpclient 
        CloseableHttpClient httpClient = HttpClients.createDefault (); 
        CloseableHttpResponse Response = null ; 
        String ResultString = "" ;
         the try {
             // Create Http Post request 
            HttpPost HttpPost = new new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

transfer

String result = HttpClientUtil.doGet(url);

The result is returned json string, and the rest is to parse the string to get the data they want it

Guess you like

Origin www.cnblogs.com/jxd283465/p/11803255.html