volley库中的意外响应代码,无法检索json字符串

时间:2016-03-29 10:39:55

标签: android json

我正在对我们创建的POSTMAN API进行json解析,我正在尝试将登录详细信息发布到POSTMAN,即: - 用户名和密码,如果细节正确,POSTMAN将在JSON STRING中返回响应。当我运行这个时,我无法获得任何类型的数据。它向我展示了意外响应代码400,406,404

MainActivity.java

package com.dropouts.copylogin;



import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
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.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;


import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;


public class MainActivity extends AppCompatActivity {
    private EditText email;
    private EditText password;
    private Button login_register;
    private RequestQueue requestQueue;
    private StringRequest request;
    private  TextView tv;
    private static String URL="http://192.168.1.18/rakyesh/test/rest/rest/login";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        email= (EditText) findViewById(R.id.user);

        password=(EditText)findViewById(R.id.pass);
        login_register=(Button)findViewById(R.id.loginbtn);
        requestQueue= Volley.newRequestQueue(this);


        login_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONObject jsonObject = new JSONObject(response);

                           Log.e("Response of 192 returns username",">"+jsonObject.getString("username"));

                            if (jsonObject.names().get(0).equals("username")) {

                                Toast.makeText(getApplicationContext(), "SUCCESS"+ jsonObject.getString("username"),Toast.LENGTH_LONG).show();
                                startActivity(new Intent(getApplicationContext(), Welcome.class));

                            } else {

                                Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {

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

                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        hashMap.put("Content-Type","application/json; charset=utf-8");
                        hashMap.put("email", email.getText().toString());
                        hashMap.put("password", password.getText().toString());
                        return hashMap;

                    }
                };
                requestQueue.add(request);

            }

        });
    }


}

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dropouts.copylogin">
<uses-permission android:name="android.permission.INTERNET"/>

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

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

</manifest>

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:layout_gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="com.dropouts.copylogin.MainActivity">



    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/user"
        android:hint="username"
        android:inputType="text"
        android:maxLines="1"
        android:singleLine="true"

        android:layout_marginTop="50dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:maxLines="1"
        android:singleLine="true"
        android:id="@+id/pass"
        android:hint="Pass"
        android:layout_marginTop="42dp"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="LOGIN/REGISTER"
        android:id="@+id/loginbtn"

        />
    <TextView
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt"
        android:textAppearance="?android:textAppearanceLarge"
        android:layout_below="@+id/loginbtn"
        /></LinearLayout>

WELCOME.JAVA

package com.dropouts.copylogin;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * Created by Pankaj on 3/17/2016.
 */
public class Welcome extends Activity {
    Button logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome_activity);
        logout= (Button) findViewById(R.id.log_out);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(getApplicationContext(),MainActivity.class));
            }
        });
    }
}

welcome_activity.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:id="@+id/wlcmtxt"
        android:textAppearance="?android:textAppearanceLarge"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:id="@+id/log_out"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

您在标题中传递application/json Content-Type并传递字符串数据。如果您想发布json数据,最好使用JsonObjectRequest。请尝试从HashMap中删除Content-Type标题。这可能会有所帮助。

<强>更新

JSONObject params = new JSONObject();
//build your params
JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.POST, url, params, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        //parse the response for the result
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
});

答案 1 :(得分:0)

以下是HttpStatus.java中的错误代码文档。

int SC_NOT_FOUND = 404;
int SC_BAD_REQUEST = 400;
int SC_NOT_ACCEPTABLE;

我提交的请求不符合标准。下面的代码应该放在'getHeaders()'方法中,而不是'getParams()'。

hashMap.put("Content-Type","application/json; charset=utf-8");

这是一个使用StringRequest的演示,通过post in volley。

https://gist.github.com/mombrea/7250835