2017-07-13 44 views
0

See Rest Client Screenshot如何同時使用查詢參數和正文。 Query中使用查詢參數,並在URL中追加。在發佈後我們提交Body。但是這個API需要兩個。API需要查詢參數和正文

URL = http://www.MYWEBSITENAME.com/api/serveVideos/serveVideosToClient.php 

QUERY PARAMS = show_by=rating&start=1&end=10 
HEADER = X-WWW-FORM-URL-ENCODED 

Request Body : 
"android_ref_id" : "14" 
"token": "1223232" 

我使用Retrofit和我得到無效的響應,但是當我使用Rest Client時,API工作正常。我也嘗試了異步任務。 這是我到目前爲止嘗試過的。但沒有運氣。

改造代碼1:

@FormUrlEncoded 
@POST("serveVideos/serveVideosToClient.php?show_by=rating&start=1&end=10") 
Call<JsonObject> serveVideosToDevice(@Field("android_ref_id") String android_uuid, @Field("token") String token); 

改造代碼2:

@FormUrlEncoded 
@POST("serveVideos/serveVideosToClient.php") 
@Headers({"Content-Type:application/x-www-form-urlencoded"}) 
Call<JsonObject> serveVideosToDevice(@QueryMap Map<String, String> options, 
            @Field("android_ref_id") String 
android_uuid, @Field("token") String token); 

改造代碼3:

@FormUrlEncoded 
    @POST("serveVideos/serveVideosToClient.php") 
    Call<JsonObject> serveVideosToDevice(@Query("show_by") String showBy, 
    @Query("start") String start, @Query("end") String end, 
    @Field("android_ref_id") String android_uuid, @Field("token") String 
    token); 

異步任務代碼

@Override 
    protected String doInBackground(String... params) { 

    URL url = null; 
    String response = null; 
    HttpURLConnection urlConnection = null; 
    String urlStr = params[0]; 
    String android_ref_id = params[2].trim(); 
    String token = params[1].trim(); 

    String urlParameters = "show_by=rating&start=1&end=10"; 
    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); 

    try { 
     url = new URL(params[0]); 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     urlConnection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded"); 
     urlConnection.setRequestMethod("POST"); 

     DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); 
     PrintWriter out = new PrintWriter(urlConnection.getOutputStream()); 

     try { 
      // wr.write(postData); 

      Map<String, String> stringMap = new HashMap<>(); 
      stringMap.put("android_ref_id", android_ref_id); 
      stringMap.put("token", token); 

      wr.writeBytes(stringMap.toString()); 
      // out.print(postData); 

      Log.e(Constants.mLogs, "Json : " + stringMap.toString()); 
      wr.flush(); 
      wr.close(); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
     response = readStream(in); 
     //readStream(in); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     urlConnection.disconnect(); 
    } 
    return response; 
} 

這兩個代碼都不起作用。在這種情況下做什麼。

+0

你可以發佈你使用改造後得到的迴應日誌嗎 – Mrinmoy

+0

我附上了postman請求樣本。請檢查。 –

回答

0

對於異步任務代碼。只要將查詢參數附加到請求URL並將其餘部分作爲正文的一部分發送,可能會更容易一些。見下文。

URL url = null; 
HttpURLConnection urlConnection = null; 
String urlStr = params[0]; 
String android_ref_id = params[2].trim(); 
String token = params[1].trim();URL url; 
String responseStr=""; 
try { 
     url = new URL(urlStr+"?show_by=rating&start=1&end=10"); 
    } catch (MalformedURLException e) { 
     throw new IllegalArgumentException("invalid url: " + urlStr); 
    } 
    params.put("android_ref_id", android_ref_id); 
    params.put("token", token); 
    StringBuilder bodyBuilder = new StringBuilder(); 
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); 
    // constructs the POST body using the parameters 
    while (iterator.hasNext()) { 
     Entry<String, String> param = iterator.next(); 
     bodyBuilder.append(param.getKey()).append('=') 
        .append(param.getValue()); 
     if (iterator.hasNext()) { 
      bodyBuilder.append('&'); 
     } 
    } 
    String body = bodyBuilder.toString(); 
    HttpURLConnection conn = null; 
    try { 
     conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setUseCaches(false); 
     conn.setChunkedStreamingMode(0); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); 
     // post the request 
     OutputStream out = conn.getOutputStream(); 
     out.write(body.getBytes()); 
     out.close(); 
     // handle the response 
     int status = conn.getResponseCode(); 
     if (status != 200) { 
      throw new IOException("Post failed with error code " + status); 
     } 
     // Get Response 
     InputStream is = conn.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 
     StringBuffer response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) { 
      response.append(line); 
     } 
     rd.close(); 
     responseStr = response.toString(); 
    } finally { 
     if (conn != null) { 
      conn.disconnect(); 
     } 
    } 
    return responseStr; 
0

試試這個:

聲明

@FormUrlEncoded 
@POST("serveVideos/serveVideosToClient.php") 
Call<JsonObject> serveVideosToDevice(@Query("show_by") String showBy, @Query("start") String start, @Query("end") String end, @Field("android_ref_id") String android_uuid, @Field("token") String token); 

呼叫

serveVideosToDevice("rating", "1", "10" ,"14", "1223232").enqueue(new Callback<JsonObject>() { 
      @Override 
      public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { 
       Log.e(this.getClass().getName(), response.toString()); 
      } 

      @Override 
      public void onFailure(Call<JsonObject> call, Throwable t) { 
       t.printStackTrace(); 
      } 
     }); 
+0

同樣的問題,我附上郵遞員請求樣本。請檢查。 –

0
@FormUrlEncoded //type application/x-www-form-urlencoded 
@POST("serveVideos/serveVideosToClient.php") // POST request to url 
Call<JsonObject> serveVideosToDevice(@QueryMap Map<String, String> options,// adding query like url?<key>=<value>&<key>=<value>... 
     @Body() RequestBody requestBody);// Json params 

Where options

{ 
    options.put("show_by", "rating") 
    options.put("start", "1") 
    options.put("end", "10") 
} 


class RequestBody{ 
    @SerializedName("android_ref_id") 
    public int refId; 
    @SerializedName("token") 
    public String token; 
} 
+0

我附上郵遞員請求樣本。請檢查。 –

+0

@Hammad Tariq停止使用'@Field()'你需要'@Body()'https://square.github.io/retrofit/2.x/retrofit/retrofit2/http/Field.html –

+0

兄弟我試過身體此外,更新了我的問題,請你再檢查一次。看看你能否以任何方式幫助我。 –