使用Java

时间:2017-05-20 09:42:31

标签: java laravel request

我正在使用Java将http请求发送到使用Laravel(5.4)创建的API。如果我发送一个没有任何特殊字符的请求,它就像一个魅力。但是如果有任何“特殊”字符,例如:é,å,ö等,那么Laravel中的请求是空的:

dd(request()->all())输出[]

我想在Java中创建请求时,这与一些错误的设置有关。我找不到解决方案。

以下是负责创建请求的代码。

public class HttpClient {

    org.apache.http.client.HttpClient client;

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

    public void post(String json) {
        try {
            HttpPost request = buildPostRequest(json);
            HttpResponse response = createClient().execute(request);

            int code = getStatusCode(response);

            if (code != 200) {
                throw new Exception("Error (" + code + ") on server.");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private org.apache.http.client.HttpClient createClient() {
        return HttpClientBuilder.create().build();
    }

    private HttpPost buildPostRequest(String json) throws Exception {
        HttpPost request = new HttpPost("some uri");
        request.addHeader("Content-type", "application/json; charset=utf-8");
        request.addHeader("Accept", "application/json");

        StringEntity params = new StringEntity(json);
        params.setContentEncoding("utf-8");
        params.setContentType("application/json; charset=utf-8");
        request.setEntity(params);

        return request;
    }

    private int getStatusCode(HttpResponse response) {
        StatusLine line = response.getStatusLine();

        return line.getStatusCode();
    }
}

修改 在请求发送到API之前转储请求。

request dump

2 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案。在buildPostRequest()方法中,我从StringEntity更改为ByteArrayEntity,并将字符串转换为UTF-8字节。

ByteArrayEntity params = new ByteArrayEntity(json.getBytes("UTF-8"));

如果我向API发送特殊字符,则请求不再为空。

答案 1 :(得分:0)

尝试这种方式

 HttpPost request = new HttpPost(URLEncoder.encode("url here", "UTF-8"));