httpclient get、post請求工具類

 

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;


public class HttpClientUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String doGET(String url, String username, String password) throws UnsupportedEncodingException {
        HttpClient client = HttpClients.custom().build();
        HttpUriRequest request = RequestBuilder.get()
                .setUri(url)
                .setHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder()
                        .encodeToString((username + ":" + password).getBytes("utf-8")))
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .build();
        try {
            HttpResponse response = client.execute(request);
            String json = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println("json===>"+json);
            return json;
        } catch (IOException e) {
            LOGGER.error("request fail", e);
        }
        return null;
    }

    public static String doPOST(String url) {
//        HttpClient client = HttpClients.custom().build();
//        HttpUriRequest request = RequestBuilder.post()
//                .setUri(url)
//
//                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
//                .build();
//        try {
//            HttpResponse response = client.execute(request);
//            String json = EntityUtils.toString(response.getEntity(), "utf-8");
//            System.out.println("json===========>" + json);
//            return json;
//        } catch (IOException e) {
//        }
//        return null;

    public static String doPOST(String url) throws UnsupportedEncodingException {
        String body = null;
        try
        {
            HttpClient client = HttpClients.custom().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept","application/json;charset=utf-8");

            JSONObject params = new JSONObject();
            params.put("newlogin","epass08");
            params.put("bizlogintoken", "9jQcGY89aG4XK5NDiOrZcp3s8SbVKYuYKV_eqlxRRm9MDPlXnA8GSG4wfC5sPtSmyN5hd_3TRJ2W2wDrxySngQ");


            // 傳值時傳遞的是json字符串,這樣的好處是在服務端無需建立參數模型,直接接收String,便於後期維護。
            StringEntity stringEntity = new StringEntity(params.toJSONString(),"utf-8");
            post.setEntity(stringEntity);

            HttpResponse response = client.execute(post);

            System.out.println("響應碼:"+response.getStatusLine());

            body = EntityUtils.toString(response.getEntity());

            System.out.println("響應body體:"+body);
        } catch (Exception e) {
            LOGGER.info("request failed {}", e);
        }
        return body;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        String username = "admin";
        String password = "f2224d2c7f9a3c126baa3b90166daeaf";

        String getUrl = "";
        String postUrl = "";

//        doGET(getUrl, username, password);

        doPOST(postUrl);

    }
}

參考:perfect:https://www.cnblogs.com/junjiang3/p/7281753.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章