Ошибка залпа сразу

Я работаю над приложением с читателем кода QR. Я пытаюсь использовать библиотеку залпа для отправки HTTP-запроса обратно на сервер. Тем не менее, он прыгает прямо к исключению ошибки строки. Это мой код,

 send.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {

Toast.makeText(QRCODEPAGE1.this, "Started", Toast.LENGTH_SHORT).show();
            RequestQueue mRequestQueue = Volley.newRequestQueue(QRCODEPAGE1.this);
            String url = "http://api-dev.eportfolioapi.com/api/sensor/plan";
          //  String url = "http://localhost:5000/api/sensor/updateDeviceStage/5b3e6e788030580019ebc333";
            Cache cache = new DiskBasedCache(getCacheDir(), 1024*1024);
            Network network = new BasicNetwork(new HurlStack());
            //mRequestQueue = new RequestQueue(cache, network);
            Toast.makeText(QRCODEPAGE1.this, "DONE", Toast.LENGTH_SHORT).show();

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    tvresult.setText("Response is:" + response.substring(0, 2000));
                    Toast.makeText(QRCODEPAGE1.this, "YOU DID IT", Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tvresult.setText("That didn't work!");
                    Toast.makeText(QRCODEPAGE1.this, "Wish harder", Toast.LENGTH_SHORT).show();
                }
            });

            //mRequestQueue.add(stringRequest);

            stringRequest.setTag(TAG);
            mRequestQueue.add(stringRequest);

Обратите внимание, что я добавил необходимые вещи в приложение Gradle и манифест.

Вот так теперь выглядит мой код...

 send.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {

 Toast.makeText(QRCODEPAGE1.this, "Make it work", Toast.LENGTH_SHORT).show();
           // Intent meow = new Intent(QRCODEPAGE1.this, QRLASTPAGE.class);
           // startActivity(meow);

            Toast.makeText(QRCODEPAGE1.this, "Started", 
  Toast.LENGTH_SHORT).show();
            RequestQueue mRequestQueue = 
  Volley.newRequestQueue(QRCODEPAGE1.this);
            String url = "http://api- 
dev.eportfolioapi.com/api/sensor/install";
            Cache cache = new DiskBasedCache(getCacheDir(), 1024*1024);
            Network network = new BasicNetwork(new HurlStack());
            //Looper.prepare();
            //mRequestQueue = new RequestQueue(cache, network);
            Toast.makeText(QRCODEPAGE1.this, "DONE", 
 Toast.LENGTH_SHORT).show();

            StringRequest request = new StringRequest(Request.Method.POST, 
 url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
Toast.makeText(QRCODEPAGE1.this, "you passed", Toast.LENGTH_SHORT).show();
        System.out.println(response.toString());
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
//Toast.makeText(QRCODEPAGE1.this, "you failed", Toast.LENGTH_SHORT).show();
        Toast.makeText(QRCODEPAGE1.this, String.valueOf(error), 
Toast.LENGTH_LONG).show();
        Log.e("Volley ERROR: ", error.toString());
       // Looper.prepare();
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
   Toast.makeText(QRCODEPAGE1.this, "Params", Toast.LENGTH_SHORT).show();
        Map<String, String> params = new HashMap<String, String>();
        params.put("userId", tvresult.getText().toString());
        Toast.makeText(QRCODEPAGE1.this, "you passed userid", 
  Toast.LENGTH_SHORT).show();
        params.put("customerId", custID.toString());
        Toast.makeText(QRCODEPAGE1.this, "you passed custid", 
  Toast.LENGTH_SHORT).show();
        params.put("sensorId", tvresult.getText().toString());
        Toast.makeText(QRCODEPAGE1.this, "sensorid", 
  Toast.LENGTH_SHORT).show();
        params.put("projectId", tvresult.getText().toString());
        Toast.makeText(QRCODEPAGE1.this, "you passed proid", 
 Toast.LENGTH_SHORT).show();
        params.put("sensorVendorID", tvresult.getText().toString());
        params.put("sensorGatewayId", tvresult.getText().toString());
       // params.put("qrCodeUrl", );
        params.put("lat", textLat.getText().toString());
        Toast.makeText(QRCODEPAGE1.this, "lat", Toast.LENGTH_SHORT).show();
        params.put("long", textLong.getText().toString());
        Toast.makeText(QRCODEPAGE1.this, "long", Toast.LENGTH_SHORT).show();
        params.put("locationWithinFacility", descprit.getText().toString());
        return params;

    }
};

            request.setTag(TAG);
            mRequestQueue.add(request);

Я получил сообщение об ошибке, сказав, что мне нужно добавить Looper.prepare(). Где я должен положить это?

1 ответ

Вы пытаетесь сделать запрос на получение, как это Request.Method.GET в то время как ваш API требует почтовый запрос, как это Request.Method.POST Кроме того, при проверке вашего API, вы должны также передать эти параметры userId, customerId, projectId, taskId, name and prTypeId

postman result

Сделайте запрос как это:

StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            System.out.println(response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

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

            Map<String, String> params = new HashMap<String, String>();
            params.put("userId", "");
            params.put("customerId", "");
            params.put("projectId", "");
            params.put("taskId", "");
            params.put("name", "");
            params.put("prTypeId", "");
            return params;
        }
    };

передать все необходимые параметры и соответствующие значения внутри getParams()

Другие вопросы по тегам