2016-09-09 2 views
0

Ich muss eine Nachricht an den Server senden. - MediaType: Anwendung/x-www-Formular-urlencodedWie stelle ich eine Postanfrage? Ich benutze OkHttp? keine Serverantwort

So habe ich FormEncodingBuilder-Klasse für die Herstellung von Körper. Ich habe diesen Code geschrieben.

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()); 
    } 

aber Server hat Parameter nicht gelesen.
Also, Server Anfrage Parameter Wert.
Wie mache ich eine Nachricht?

Antwort

0

Vielleicht müssen Sie Zeichensatz setzen.
, aber die FormEncodingBuilder-Klasse verwendet nur MediaType "application/x-www-form-urlencoded".
So können Sie neue Klasse wie FormEncodingBuilder machen.

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); 
    } 
}} 

Nachdem Sie formbody mit dieser Klasse, versuchen an den Server senden