【问题标题】:How do I make a post request? I use OkHttp? no server response如何提出发帖请求?我使用 OkHttp 吗?没有服务器响应
【发布时间】:2017-01-17 01:00:42
【问题描述】:

我需要向服务器发布消息。 - MediaType : application/x-www-form-urlencoded

所以,我使用 FormEncodingBuilder 类来制作正文。 我写了这段代码。

Uri.Builder uri = new Uri.Builder()
            .scheme(SCHEME)
            .encodedAuthority(HOST)
            .appendPath("v3")
            .appendPath("svc")
            .appendPath("auth");

    FormEncodingBUilderformBody = new FormEncodingBUilder()
            .add("name", data.getName())
            .add("gender", data.getGender())
            .build();

    Request request = new Request.Builder()
            .url(uri.build().toString())
            .post(formBody)
            .build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        String body = response.body().string();

        return body;
    } catch (Exception e) {
        throw new ApiException(0, e.toString());
    }

但是服务器没有读取参数。
所以,服务器请求参数的值。
如何发消息?

【问题讨论】:

    标签: android okhttp


    【解决方案1】:

    也许您需要设置字符集。
    但 FormEncodingBuilder 类仅使用 MediaType“application/x-www-form-urlencoded”。
    因此,您可以创建像 FormEncodingBuilder 这样的新类。

    public class OkHttpFormBuilder {
    
    private MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
    private final StringBuilder content = new StringBuilder();
    
    
    public OkHttpFormBuilder() {
    }
    
    public MediaType getCONTENT_TYPE() {
        return CONTENT_TYPE;
    }
    
    public void setCONTENT_TYPE(MediaType CONTENT_TYPE) {
        this.CONTENT_TYPE = CONTENT_TYPE;
    }
    
    public OkHttpFormBuilder add(String name, String value) {
        if(this.content.length() > 0) {
            this.content.append('&');
        }
    
        try {
            this.content.append(URLEncoder.encode(name, "UTF-8")).append('=').append(URLEncoder.encode(value, "UTF-8"));
            return this;
        } catch (UnsupportedEncodingException var4) {
            throw new AssertionError(var4);
        }
    }
    
    public String getContent()
    {
        return this.content.toString();
    }
    
    public RequestBody build() {
        if(this.content.length() == 0) {
            throw new IllegalStateException("Form encoded body must have at least one part.");
        } else {
            byte[] contentBytes = this.content.toString().getBytes(Util.UTF_8);
            return RequestBody.create(CONTENT_TYPE, contentBytes);
        }
    }}  
    

    使用该类制作formbody后,尝试发送到服务器

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 2018-06-26
      • 1970-01-01
      • 2020-08-19
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      相关资源
      最近更新 更多