封装RestfulOperResult类

20 篇文章 2 订阅
3 篇文章 0 订阅
该代码段展示了如何使用Apache HttpClient库执行RESTful API的HTTP方法,包括POST、GET、PUT和DELETE。方法中设置请求头,如授权、内容类型和接受类型,并处理响应内容。此外,还定义了一个`RestfulOperResult`类来存储HTTP状态码和返回的字符串。
摘要由CSDN通过智能技术生成
<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>
package com.cncr.dcontroller.restinvoke;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class RestfulOper {

    private static final Logger LOG = LoggerFactory.getLogger(RestfulOper.class);

    public static String post(String url, String inputInfo) {
        LOG.debug("post, url:{}, input:{}", url, inputInfo);
        try {
            HttpClient httpClient = HttpClients.createDefault();
            url = url.replace(" ", "%20");
            HttpPost httpPostRequest = new HttpPost(url);

            String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
            httpPostRequest.setHeader("Authorization", "Basic " + encoding);
            httpPostRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPostRequest.setHeader("Accept", "application/json, text/plain,");

            // 将参数进行封装,提交到服务器端
            StringEntity se = new StringEntity(inputInfo, Charset.forName("UTF8"));
            httpPostRequest.setEntity(se);
            HttpResponse response = httpClient.execute(httpPostRequest);
            response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
                String str = scanner.useDelimiter("\\A").next();
                LOG.trace(str);
                return str;
            } catch (Exception e) {
                LOG.error("url:{}, input:{}, error message:{}", url, inputInfo, ExceptionUtils.getStackTrace(e));
            }
        } catch (Exception e) {
            LOG.error("url:{}, input:{}, error message:{}", url, inputInfo, ExceptionUtils.getStackTrace(e));
        }
        return "";
    }

    public static RestfulOperResult postNew(String url, String inputInfo) throws ClientProtocolException, IOException {
        LOG.debug("post, url:{}, input:{}", url, inputInfo);
        HttpClient httpClient = HttpClients.createDefault();
        url = url.replace(" ", "%20");
        HttpPost httpPostRequest = new HttpPost(url);

        String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        httpPostRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPostRequest.setHeader("Accept", "application/json, text/plain,");

        // 将参数进行封装,提交到服务器端
        StringEntity se = new StringEntity(inputInfo, Charset.forName("UTF8"));
        httpPostRequest.setEntity(se);
        HttpResponse response = httpClient.execute(httpPostRequest);
        HttpEntity entity = response.getEntity();
        try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
            String str = scanner.useDelimiter("\\A").next();
            LOG.trace(str);
            return new RestfulOperResult(response.getStatusLine().getStatusCode(), str);
        } catch (NoSuchElementException e) {
            return new RestfulOperResult(response.getStatusLine().getStatusCode(), response.getStatusLine().toString());
        }
    }

    public static String delete(String url) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            url = url.replace(" ", "%20");
            HttpDelete httpPostRequest = new HttpDelete(url);

            String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
            httpPostRequest.setHeader("Authorization", "Basic " + encoding);
            httpPostRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPostRequest.setHeader("Accept", "application/json, text/plain,");

            HttpResponse response = httpClient.execute(httpPostRequest);
            HttpEntity entity = response.getEntity();
            try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
                String str = scanner.useDelimiter("\\A").next();
                LOG.trace(str);
                return str;
            } catch (Exception e) {
                LOG.error("url:{}, error message:{}", url, ExceptionUtils.getStackTrace(e));
            }
        } catch (Exception e) {
            LOG.error("url:{}, error message:{}", url, ExceptionUtils.getStackTrace(e));
        }
        return "";
    }

    public static String put(String url, String inputInfo) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            url = url.replace(" ", "%20");
            HttpPut httpPostRequest = new HttpPut(url);

            String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
            httpPostRequest.setHeader("Authorization", "Basic " + encoding);
            httpPostRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPostRequest.setHeader("Accept", "application/json, text/plain,");

            // 将参数进行封装,提交到服务器端
            StringEntity se = new StringEntity(inputInfo, Charset.forName("UTF8"));
            httpPostRequest.setEntity(se);
            HttpResponse response = httpClient.execute(httpPostRequest);
            HttpEntity entity = response.getEntity();
            try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
                String str = scanner.useDelimiter("\\A").next();
                LOG.trace(str);
                return str;
            } catch (Exception e) {
                LOG.error("url:{}, input:{}, error message:{}", url, inputInfo, ExceptionUtils.getStackTrace(e));
            }
        } catch (Exception e) {
            LOG.error("url:{}, input:{}, error message:{}", url, inputInfo, ExceptionUtils.getStackTrace(e));
        }
        return "";
    }

    public static String get(String url) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            url = url.replace(" ", "%20");
            HttpGet httpPostRequest = new HttpGet(url);

            String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
            httpPostRequest.setHeader("Authorization", "Basic " + encoding);
            httpPostRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPostRequest.setHeader("Accept", "application/json, text/plain,");

            HttpResponse response = httpClient.execute(httpPostRequest);
            HttpEntity entity = response.getEntity();
            try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
                String str = scanner.useDelimiter("\\A").next();
                LOG.trace(str);
                return str;
            } catch (Exception e) {
                LOG.error("url:{}, error message:{}", url, ExceptionUtils.getStackTrace(e));
            }
        } catch (Exception e) {
            LOG.error("url:{}, error message:{}", url, ExceptionUtils.getStackTrace(e));
        }
        return "";
    }
}

package com.cncr.dcontroller.restinvoke;

public class RestfulOperResult {
    private int status;
    private String returnStr;

    public boolean isResult() {
        return status == 200;
    }

    public RestfulOperResult(int status, String returnStr) {
        super();
        this.status = status;
        this.returnStr = returnStr;
    }

    @Override
    public String toString() {
        return "RestfulOperResult [status=" + status + ", returnStr=" + returnStr + "]";
    }

    public int getStatus() {
        return status;
    }

    public String getReturnStr() {
        return returnStr;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值