如何实现Imgflip API的post方法?

问题描述 投票:0回答:1

我试图在android studio上创建一个应用程序,我是这个IDE和语言的新手,我设法实现了Imflip api的GET方法,但我卡在了POST方法上。我设法实现了Imflip api的GET方法,但我卡在了POST方法上。我想返回一个带有用户添加的标题的Meme。

我使用的是Android Studio 3.4.1。我已经尝试了附件中的代码。为了测试,我已经硬编码了用户名、密码和两个标题。另外,当我调用POST()时,我把ID 61579作为一个参数。我试着找到响应的值,但它说它是 "200"... ...

我需要的是一个创建meme的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();
    }

}
java android api
1个回答
0
投票

从编码=切换 "json" 编码 = "form"

或者把你的身体换成 BodySerializationMethod.UrlEncoded 行得通

© www.soinside.com 2019 - 2024. All rights reserved.