Java HttpURLConnection cannot set Content-Length

34 views Asked by At

Java network request problem,I'm trying to call an interface that gets a list of user data, which requires a POST transfer and Content-Length in the request header, but my code won't work

public static HttpURLConnection prepare(String address, List<NameValuePair> heads) throws Exception {
    URL url = new URL(address);
    HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
    httpUrlConnection.setUseCaches(false);
    Map<String, String> map = new HashMap<>();
    map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_CREDENTIALS,
            ConnectionAction.ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
    try {
        map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_HEADERS,
                ConnectionAction.ACCESS_CONTROL_ALLOW_HEADERS_VALUE + ", " + Config.person().getTokenName());
    } catch (Exception e) {
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug(e.getMessage());
        }
    }
    map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_METHODS, ConnectionAction.ACCESS_CONTROL_ALLOW_METHODS_VALUE);
    map.put(ConnectionAction.CACHE_CONTROL, ConnectionAction.CACHE_CONTROL_VALUE);
    map.put(ConnectionAction.CONTENT_TYPE, ConnectionAction.CONTENT_TYPE_VALUE);
    for (NameValuePair o : ListTools.nullToEmpty(heads)) {
        map.put(o.getName(), Objects.toString(o.getValue()));
    }
    for (Entry<String, String> en : map.entrySet()) {
        if (StringUtils.isNotEmpty(en.getValue())) {
            httpUrlConnection.setRequestProperty(en.getKey(), en.getValue());
        }
    }
    return httpUrlConnection;
}

public static <T> T postAsString(String address, List<NameValuePair> heads, String body, Class<T> cls) throws Exception {
    HttpURLConnection connection = prepare(address, heads);
    connection.setRequestMethod(ConnectionAction.METHOD_POST);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setConnectTimeout(DEFAULT_CONNECTTIMEOUT);
    connection.setReadTimeout(DEFAULT_READTIMEOUT);
    connection.connect();
    doOutput(connection, body);
    String str = readResultString(connection);
    connection.disconnect();
    return XGsonBuilder.instance().fromJson(str, cls);
}

private static void doOutput(HttpURLConnection connection, String body) throws Exception {
    try (OutputStream output = connection.getOutputStream()) {
        if (StringUtils.isNotEmpty(body)) {
            IOUtils.write(body, output, StandardCharsets.UTF_8);
            output.flush();
        }
    }
}

public static String readResultString(HttpURLConnection connection) throws Exception {
    String result = "";
    try (InputStream input = connection.getInputStream()) {
        result = IOUtils.toString(input, StandardCharsets.UTF_8);
    }
    int code = connection.getResponseCode();
    if (code != 200) {
        throw new IllegalStateException("connection{url:" + connection.getURL() + "}, response error{responseCode:"
                + code + "}, response:" + result + ".");
    }
    return result;
}


private List<User> getUsers() throws Exception {
    Post post = new Post();
    post.setEid("111");
    List<NameValuePair> heads = new ArrayList<>();
    heads.add(new NameValuePair("Content-Type", "application/x-www-form-urlencoded"));
    heads.add(new NameValuePair("Transfer-Encoding", "chunked"));
    String address = Config.getApiAddress() + "/gateway/open/userlist?accessToken=" + this.accessToken;
    UserListResp resp = HttpConnection.postAsString(address, heads, post.toString(), UserListResp.class);
}


public static class UserListResp extends GsonPropertyObject {

    private Integer errorCode;
    private String error;
    private Boolean success;
    private List<User> data;

    public Integer getErrcode() {
        return errorCode;
    }

    public void setErrcode(Integer errcode) {
        this.errorCode = errcode;
    }

    public String getErrmsg() {
        return error;
    }

    public void setErrmsg(String errmsg) {
        this.error = errmsg;
    }

    public void setSuccess(Boolean success){
        this.success = success;
    }
    public Boolean getSuccess(){
        return this.success;
    }

    public List<User> getUserlist() {
        return data;
    }

    public void setUserlist(List<User> userlist) {
        this.data = userlist;
    }

}

public static class OrgPost extends GsonPropertyObject {

    private String eid;

    public String getEid() {
        return eid;
    }

    public void setEid(String eid) { this.eid = eid; }
}

I call the getUsers function of the above code, and the server always returns the error data, which is caused by not carrying Content-Length, I tried to carry Content-Length or Transfer-Encoding to solve this problem, but it does not work

0

There are 0 answers