如何同時使用查詢參數和正文。 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;
}
這兩個代碼都不起作用。在這種情況下做什麼。
你可以發佈你使用改造後得到的迴應日誌嗎 – Mrinmoy
我附上了postman請求樣本。請檢查。 –