Android Volley:无论如何,如何从服务器获取响应?

时间:2019-06-27 02:45:36

标签: android kotlin android-volley

我开始使用Kotlin开发Android。我正在尝试使用Volley来读取API和更新GUI元素。我使它与使用http GET方法的StringObjectRequests一起使用,现在的问题是当我想使用POST方法时使用。

这是我的基本功能:

fun volley() {
    val queue = Volley.newRequestQueue(this)
    val url   = "http://x.x.x.x/api.php"
    val json = JSONObject()

    json.put("ciudad", "Londres")
    json.put("nombre", "Luis")

    val stringRequest = JsonObjectRequest(Request.Method.POST,
      url, json,
      Response.Listener<JSONObject> { response ->
        taContenido.setText(response.toString())
      },
      Response.ErrorListener {
        taContenido.setText("No Funcionó")
      })

    queue.add(stringRequest)
  }

“ API”中的代码非常简单...

<?php
$j = array('ciudad' => $_POST["ciudad"],
   'nombre' => $_POST["nombre"]);

echo json_encode($j);

我的问题是,当我运行该函数时,它会通过ErrorListener部分并显示“ NoFuncionó”。我不知道为什么。当然,如果我用Postman尝试API,它将返回预期的{"ciudad":"Londres","nombre":"Luis"}

那么,在使用JsonObjectRequest时,如何查看服务器返回什么信息?

如果我将Request更改为StringRequest,那么我当然可以看到PHP错误(因为将没有定义$ _POST []:|

1 个答案:

答案 0 :(得分:-1)

我正在用Java发布。请转换为Kotlin。像这样制作一个单例课程-

public class VolleyManager {
    private static VolleyManager ourInstance;
    private final Context mContext;
    private final ImageLoader mImageLoader;
    private RequestQueue mRequestQueue;

    private VolleyManager(final Context pContext) {
        mContext = pContext;
        mImageLoader = new ImageLoader(getRequestQueue(), new ImageLoader.ImageCache() {
            private LruCache<String, Bitmap> mCache = new LruCache<>(20);

            @Override
            public Bitmap getBitmap(final String url) {
                return mCache.get(url);
            }

            @Override
            public void putBitmap(final String url, final Bitmap bitmap) {
                mCache.put(url, bitmap);
            }
        });
    }

    private RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mContext);
        }
        return mRequestQueue;
    }

    public static synchronized VolleyManager getInstance(final Context pContext) {
        if (ourInstance == null) {
            ourInstance = new VolleyManager(pContext);
        }
        return ourInstance;
    }

    public void addRequest(final Request pRequest) {
        getRequestQueue().add(pRequest);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(tag);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

并发出这样的请求-

public class AccessTokenRequest extends StringRequest {
    Map<String,String> mParms = new ArrayMap<>();
    Map<String,String> mHeader = new ArrayMap<>();

    public AccessTokenRequest(String code, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(Method.POST, WebConfig.END_POINT + WebConfig.ACCESS_TOKEN_METHOD, listener, errorListener);
        mHeader.put("Authorization","Basic MjJEUT");
        mHeader.put("Content-Type","application/x-www-form-urlencoded");
        mParms.put("clientId","63FGDF");
        mParms.put("grant_type","authorization_code");
        mParms.put("redirect_uri","https://example.com/thu");
        mParms.put("code",code);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mHeader;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParms;
    }
}

在活动中,像这样打电话-

private void requestAccessToken(String code) {

        final ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.show();

        VolleyManager.getInstance(AuthorizationActivity.this).addRequest(new AccessTokenRequest(code, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject responseJsonObj = new JSONObject(response);
                    String accessToken = responseJsonObj.getString("access_token");
                    long expiresIn = responseJsonObj.getInt("expires_in") + (System.currentTimeMillis() / 1000);
                    String refreshToken = responseJsonObj.getString("refresh_token");
                    List<Scope> scopes = parseScopes(responseJsonObj.getString("scope"));
                    String tokenType = responseJsonObj.getString("token_type");
                    String userId = responseJsonObj.getString("user_id");



                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    pDialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pDialog.dismiss();
                Toast.makeText(AuthorizationActivity.this, "Please check internet connection", Toast.LENGTH_LONG).show();
            }
        }));
    }