基於HttpClient Jar包封裝Java方法實現介面測試__Java

來源:互聯網
上載者:User
import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import org.apache.commons.lang.StringUtils;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpDelete;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpPut;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.CoreConnectionPNames;import org.apache.http.util.EntityUtils;@SuppressWarnings("deprecation")public class HttpTools {    public static void main(String[] args) {        HttpTools ht = new HttpTools("http://www.baidu.com", "GET");        if (ht.sendRequest()) {            System.out.println(ht.getResponseBody());            System.out.println(ht.getResponseCode());        }    }    private String apiUrl;    private HttpClient client = null;    private StringEntity entity = null;    private HttpResponse response = null;    private String method = "";    private String path = "";    private String param = "";    private String fragment;    private int code;    private String body;    private String requestBody;    private Map<String, String> headers = new HashMap<String, String>();    private StringBuffer sb = new StringBuffer();    public HttpTools(String apiUrl, String method) {        this.apiUrl = apiUrl;        this.method = method;    }    public String path(String path) {        this.path = path.trim();        return this.path;    }    public void param(String key, String value) {        if (!StringUtils.isBlank(this.param)) {            this.param += "&";        }        this.param += key.trim() + "=" + value.trim();    }    public void fragment(String info) {        sb.append(info);    }    public void headers(String key, String value) {        this.headers.put(key.trim(), value.trim());    }    public void body(String requestBody) {        this.requestBody = requestBody.trim();    }    public boolean sendRequest() {        boolean flag = false;        try {            client = new DefaultHttpClient();            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 600000);            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 600000);            if (!StringUtils.isBlank(path)) {                apiUrl += path;            }            if (!StringUtils.isBlank(param)) {                apiUrl += "?" + param;            }            if (!StringUtils.isBlank(fragment)) {                apiUrl += "#" + fragment;            }            if (!StringUtils.isBlank(requestBody)) {                entity = new StringEntity(requestBody);            }            if (method.equalsIgnoreCase("GET")) {                HttpGet get = new HttpGet(apiUrl);                if (!this.headers.isEmpty()) {                    for (Entry<String, String> header : headers.entrySet()) {                        get.addHeader(header.getKey(), header.getValue());                    }                }                response = client.execute(get);            } else if (method.equalsIgnoreCase("POST")) {                HttpPost post = new HttpPost(apiUrl);                if (!this.headers.isEmpty()) {                    for (Entry<String, String> header : headers.entrySet()) {                        post.addHeader(header.getKey(), header.getValue());                    }                }                post.setEntity(entity);                response = client.execute(post);            } else if (method.equalsIgnoreCase("PUT")) {                HttpPut put = new HttpPut(apiUrl);                if (!this.headers.isEmpty()) {                    for (Entry<String, String> header : headers.entrySet()) {                        put.addHeader(header.getKey(), header.getValue());                    }                }                put.setEntity(entity);                response = client.execute(put);            } else if (method.equalsIgnoreCase("DELETE")) {                HttpDelete delete = new HttpDelete(apiUrl);                if (!this.headers.isEmpty()) {                    for (Entry<String, String> header : headers.entrySet()) {                        delete.addHeader(header.getKey(), header.getValue());                    }                }                response = client.execute(delete);            }            HttpEntity entity = response.getEntity();            body = EntityUtils.toString(entity);        } catch (Exception e) {        }        int code = response.getStatusLine().getStatusCode();        this.code = code;        if (response != null)            flag = true;        client.getConnectionManager().shutdown();        return flag;    }    public String getResponseBody() {        System.out.println("The response body is " + body);        return body;    }    public int getResponseCode() {        System.out.println("The response code is " + code);        return code;    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.