我正在尝试在android studio上创建一个应用,并且是该IDE和语言的新手。我设法为Imflip api实现了GET方法,但是我陷入了POST方法。我想返回一个由用户添加标题的Meme。
我正在使用Android Studio 3.4.1。我已经尝试了所附的代码。为了进行测试,我对用户名,密码和两个标题进行了硬编码。另外,当我调用POST()时,我将id 61579作为参数传递。我试过发现他对响应很重视,但它表示响应为“ 200” ...
我需要的是创建的模因的URL。
希望任何人都可以提供帮助。 预先感谢。
private void POST(String memeID) {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "https://api.imgflip.com/caption_image";
JSONObject jsonBody = new JSONObject();
jsonBody.put("template_id", memeID);
jsonBody.put("username", "Meme_Genie");
jsonBody.put("password", "Password");
jsonBody.put("text0", "Hello");
jsonBody.put("text1", "World");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
从encode = "json"
切换为encode = "form"
或者将您的身体切换为BodySerializationMethod.UrlEncoded
即可