使用HttpClient进行http请求(一切ajax请求都改造成HttpClient方式)

 1.项目中最近需要在后端访问外部系统接口,原本在前端可以用ajax发送的访问请求要改造成后端http访问,于是在网上搜了一下相关资料,最终采用了HttpClient。

2.以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。

(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器

3.演示代码如下:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
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.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
    /**
     * 使用HttpClient进行http get请求
     */
    public static void get(String url) {
        /**
         * client和response需要关闭资源
         */
        // 创建client,放入try()中自动释放,不需要finally
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

            // 执行得到response
            try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
                // 获取statusCode
                Integer statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // body
                    String bodyAsString = EntityUtils.toString(entity);
                    // Media Type
                    String contentMimeType = ContentType.getOrDefault(entity).getMimeType();
                    // head
                    Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
                    // 输出
                    System.out.println("statusCode:" + statusCode);
                    System.out.println("contentMinmeType:" + contentMimeType);
                    System.out.println("body:" + bodyAsString);
                    System.out.println("head" + headers);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 使用HttpClient进行http post请求
     * @param url  请求url
     * @param params  请求参数
     * @return
     */
    public static JSONObject post(String url,List<NameValuePair> params) {
         JSONObject ret =  new JSONObject();
        // 创建client
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            //添加请求url
            HttpPost postRequest = new HttpPost(url);
            // 添加请求参数
           /* List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("_SRVNAME", "server.app.loginAPI"));
            params.add(new BasicNameValuePair("_SRVMETHOD", "verifyAccount"));
            params.add(new BasicNameValuePair("_DATA", str));*/
            postRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
            // 执行并获取返回结果到response
            try (CloseableHttpResponse response = client.execute(postRequest)) {
                // 获取statusCode
                Integer statusCode = response.getStatusLine().getStatusCode();
                // Media Type
                String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
                // body
                String bodyAsString = EntityUtils.toString(response.getEntity());
                // head
                Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
                System.out.println("return time:" + new Date());
                System.out.println("statusCode:" + statusCode);
                System.out.println("contentMinmeType:" + contentMimeType);
                System.out.println("body:" + bodyAsString);
                System.out.println("head" + headers);
                ret = JSONObject.fromObject(bodyAsString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static void main(String[] args) {
      System.out.println("----------------开始--------------------");
          //根据外部系统定义的接口组织接口需要的参数
        JSONObject jo = new JSONObject();
        JSONObject jo2 = new JSONObject();
        jo2.put("type", "01");
        jo2.put("loginname", "admin");
        jo2.put("password", "123456");
        jo.put("form", jo2);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("_SRVNAME", "server.app.loginAPI"));
        params.add(new BasicNameValuePair("_SRVMETHOD", "verifyAccount"));
        params.add(new BasicNameValuePair("_DATA", jo.toString()));
        String url = "http://192.168.81.107:8080/nl-app-lx/wdk?action=wdk.pub&method=call_service&ajaxparam="+new Date().getTime();
       //调用工具方法
        JSONObject ret =  post(url,params);
        //输出返回数据
        System.out.println(ret.optString("code"));
        System.out.println(ret.optString("desc"));
        JSONObject result =  ret.optJSONObject("result");
        System.out.println(result.optString("account_id"));
        System.out.println(result.optString("account_name"));
        System.out.println(result.optString("user_name"));
    }
}//代码演示结束

4.main方法RUN AS跑起来后,控制台输出的信息如下所示:

猜你喜欢

转载自blog.csdn.net/u012880682/article/details/84989085