安卓:Volley请求不起作用

6

我是一名新手,想学习关于Android和Volley的知识。

我创建了一个登录程序,用于从我的服务器获取JSON数据,但它无法正常工作。

点击登录按钮后,它没有显示JSON响应。

以下是我的代码:

MainActivity.java

package com.volley.cuser.volleyexample;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends Activity {

    private TextView txtDisplay;
    EditText editText;
    EditText editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.username);
        editText2 = (EditText) findViewById(R.id.password);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void studentLogin(View view) {
        String username = editText.getText().toString();
        String password = editText2.getText().toString();
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = "http://afterklass.in/api/";
        JSONObject js = new JSONObject();
        try {
            JSONObject jsonobject = new JSONObject();

            jsonobject.put("email_mobile", username);
            jsonobject.put("passwd", password);
            jsonobject.put("m", "student");
            jsonobject.put("uc", "signin");
            jsonobject.put("signin", "Sign+In");

            js.put("data", jsonobject.toString());

        }catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, js, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                // TODO Auto-generated method stub
                txtDisplay.setText("Response => " + response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //String json = null;

                //NetworkResponse response = error.networkResponse;
                //if(response != null && response.data != null){
                    //switch(response.statusCode){
                        //case 400:
                            //txtDisplay.setText("Error => " + response.data);
                            //break;
                    //}
                    //txtDisplay.setText("Error => " + response.statusCode);
                    //Additional cases
                //}
                Log.d("ERROR", error.toString());
            }
        });

        queue.add(jsObjRequest);
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/username" />
    <EditText android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/login"
        android:onClick="studentLogin" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.volley.cuser.volleyexample" >

    <uses-permission android:name="android.permission.INTERNET"/>'

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

1
什么是错误信息? - Pankaj
我没有收到任何错误信息。 - Shivam
@Shivam:它没有重定向到其他页面,启动新Activity的代码在哪里? - ρяσѕρєя K
1
尝试进行调试,以查看是否调用了onErrorResponse或onResponse。 - BNK
@BNK,我无法理解。你的意思是什么? - Shivam
显示剩余16条评论
6个回答

4
请将您的jsonRequest更改为StringRequest,并向其添加自定义标头:
private static final String TAG = YourActivity.class.getSimpleName();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Display the first 500 characters of the response string.
                Log.e(TAG, "Successfully signed in : " + response.toString());
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Error at sign in : " + error.getMessage());
    }
}) {
    @Override
    public HashMap<String, String> getParams() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("email_mobile", username);
        params.put("passwd", password);
        params.put("m", "student");
        params.put("uc", "signin");
        params.put("signin", "Sign+In");
        return params;
    }
};

谢谢。

谢谢你的帮助,Mamata。我的程序现在可以正常工作了。希望以后还能得到你的帮助。 :) - Shivam
有人能帮我解决这个问题吗?http://stackoverflow.com/questions/34367435/volley-getting-a-error-response-in-5-1-1-but-working-perfectly-in-android-4 - Abhigyan

3
在 Android Manifest 文件中的一行:
<uses-permission android:name="android.permission.INTERNET"/>'

删除行末的单引号


2

改为以下一行代码:

 RequestQueue queue = Volley.newRequestQueue(this);

将其更改为以下内容:

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

onCreate 方法中声明你的 EditText 如下:

EditText editText;
EditText editText2;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.username);
        editText2 = (EditText) findViewById(R.id.password);
  }

请在您的 public void onErrorResponse(VolleyError error) 方法中检查是否有任何错误(Error)信息。 - Pankaj
只需打印日志 **Log.d("ERROR",error.toString()); 并暂时注释掉其他代码。 - Pankaj
09-15 11:44:40.428 3282-3282/com.volley.cuser.volleyexample D/ERROR﹕ com.android.volley.ParseError: org.json.JSONException: 值类型为java.lang.String的<!DOCTYPE无法转换为JSONObject。 - Shivam
尝试使用 StringRequest 而不是 JsonObjectRequest - Pankaj
让我们在聊天中继续这个讨论 - Shivam
显示剩余3条评论

1
当您发送JSON数据时,请设置内容类型如下... 希望这可以帮助到您。
    @Override
    public Map<String, String> getHeaders ()
    throws AuthFailureError {
        Map<String, String> params = new HashMap<String,
                String>();
        params.put("Content-Type", "application/json");
        return params;
    }

不,我不知道如何检查。我对此还很陌生,请帮忙。 - Shivam
在每个语句后面加上System.out.println("任何消息"),并检查它停止的位置(即执行停止并且未打印您的消息的位置)。 - Mahesh B ツ
我明白了。这些参数将作为JsonObject发送,并在Web服务中处理为普通的POST参数。我们能否使用JsonObjectRequest发送普通的POST参数?感谢您的所有努力。 - Shivam
是的,就像getHeaders()方法一样,还有一个getParams()方法,您可以在其中使用HashMap<String, String>发送参数。 - Mahesh B ツ
我们能在安卓端做些什么来处理它吗?因为我无法更改那些API。 - Shivam
显示剩余3条评论

0
将以下内容添加到您的build.gradle文件中:

compile 'com.mcxiaoke.volley:library:1.0.19'


0

你也可以这样做:

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("email_mobile", username);
    params.put("passwd", password);

    JSONObject parameters = new JSONObject(params);

    JsonObjectRequest newRequest = new JsonObjectRequest(Request.Method.POST, URL, parametres, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

在这里,我们将对象传递给构造函数以获取正确的响应。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接