首页 > 解决方案 > 如何将 HttpGet 更改为 HttpPost?

问题描述

我是 Java 新手,我正在缓慢但肯定地学习;对此的任何见解将不胜感激。

我有一些功能性的 HttpGet 代码,我想将其适配到 HttpPost 中,以便我可以打开并发送本地 JSON 文件的内容。我尝试了很多方法,但都失败了,我现在很困惑。

这是我到目前为止转换的 HttpPost 代码。它只有 HttpGet 到 HttpPost 的变化。import org.apache.http.client.methods.HttpPost;存在。我应该做什么?

@Component
public class ServiceConnector {
    private final HttpClient client;

    public ServiceConnector() {
        client = HttpClientBuilder.create().build();
    }

    public String post(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
        HttpPost request = new HttpPost(url);
        request.addHeader("Accept", acceptHeader);
        if (bearerToken.isPresent()) {
            request.addHeader("Authorization", "Bearer " + bearerToken.get());
        }

        try {
            HttpResponse response = client.execute(request);

            if (response.getStatusLine().getStatusCode() == 401) {
                throw new UnauthorizedException();
            }
            return EntityUtils.toString(response.getEntity());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

在“get”存在的地方用“post”编辑。

标签: javahttpclient

解决方案


您可以尝试这样的事情,在其中使用 JSON 准备发布请求,然后执行它:

@Component
public class ServiceConnector {
    private final HttpClient client;


    public ServiceConnector() {
        client = HttpClientBuilder.create().build();
    }
    public String post(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {

    try {
        HttpPost request = new HttpPost(url);
        request.addHeader("Accept", acceptHeader);
        if (bearerToken.isPresent()) {
            request.addHeader("Authorization", "Bearer " + bearerToken.get());
        }
        StringEntity params =new StringEntity("details {\"name\":\"myname\",\"age\":\"20\"} ");
    // You could open, read, and convert the file content into a json-string (use GSON lib here)
        request.addHeader("content-type", "application/json");
        request.addHeader("Accept","application/json");
        request.setEntity(params);
        HttpResponse response = client.execute(request);

        // handle response here...
    }catch (Exception ex) {
        // handle exception here
    } finally {
        client.getConnectionManager().shutdown();
    }
}

推荐阅读