2016-03-02 58 views
10

我已經使用這種方法https://stackoverflow.com/a/31744565/5829906但不發佈數據。如何使用內容類型爲x-www-form-urlencoded的okhttp庫發佈數據?

這裏是我的代碼

OkHttpClient client = new OkHttpClient(); 
     RequestBody requestBody = new MultipartBuilder() 
       .type(MultipartBuilder.FORM) 
       .addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome") 
       .build(); 
     Request request = new Request.Builder() 
       .url(url) 
       .post(requestBody) 
       .build(); 
     try { 

      Response response = client.newCall(request).execute(); 
      String responseString = response.body().string(); 
      response.body().close(); 
     }catch (Exception e) { 
      e.printStackTrace(); 
     } 

我試過DefaultHttpClient,這似乎是工作,但它表明棄用,因此想嘗試的東西different..Cant弄清楚什麼是錯的這個

回答

11

您可以選擇MediaType MultipartBuilder.FORM 這是文件/圖片上傳的多

public static final MediaType FORM = MediaType.parse("multipart/form-data"); 

嘗試這樣發送的

private final OkHttpClient client = new OkHttpClient(); 
public void run() throws Exception { 
    RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build(); 
    Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build(); 
    Response response = client.newCall(request).execute(); 
    if (!response.isSuccessful()) 
     throw new IOException("Unexpected code " + response); 
    System.out.println(response.body().string()); 
} 

相關問題