如何将HttpGet更改为HttpPost?

时间:2019-03-13 13:31:10

标签: java httpclient

我是Java的新手,但是我正在学习,但是我确实很慢。任何对此的见识将不胜感激。

我有一些想要转换为HttpPost的功能性HttpGet代码,以便我可以打开并发送本地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”编辑。

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的方法,在该示例中,使用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();
    }
}