Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android中登录的空JSON响应_Android_Json - Fatal编程技术网

Android中登录的空JSON响应

Android中登录的空JSON响应,android,json,Android,Json,我正在使用android进行注册和从服务器登录。注册已成功完成,但登录时给出空响应 我的登录页面如下: package com.example.arunraj.locationtracker; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import a

我正在使用android进行注册和从服务器登录。注册已成功完成,但登录时给出空响应

我的登录页面如下:

package com.example.arunraj.locationtracker;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


public class MainActivity extends ActionBarActivity {
    String L_URL= "http://safetracker-threetinker.rhcloud.com/api/login";
    EditText e_user,e_pwd;
    String c_username,c_password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        e_user = (EditText) findViewById(R.id.e_user);
        e_pwd = (EditText) findViewById(R.id.e_pwd);
        Button b_login = (Button) findViewById(R.id.b_login);
        Button b_register = (Button) findViewById(R.id.b_register);
        b_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                c_username=e_user.getText().toString();
                c_password=e_pwd.getText().toString();
                LoginAsyn loginAsyn=new LoginAsyn();
                loginAsyn.execute(L_URL);
//
            }
        });
        b_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(i);
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it i present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    class LoginAsyn extends AsyncTask<String,Void,String>
    {
        private ProgressDialog nDialog;






        @Override
        protected void onPreExecute()
        {

            //progress dialog
            nDialog = new ProgressDialog(MainActivity.this);
            nDialog.setMessage("Loading..");
            nDialog.setTitle("Login....");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            InputStream inputStream = null;
            String result = "";
            try {
                // 1. create HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost(params[0]);
                String json = "";
                // 3. build jsonObject
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", c_username);
                jsonObject.put("password", c_password);


                // 4. convert JSONObject to JSON to String
                json = jsonObject.toString();

                // 5. set json to StringEntity
                StringEntity se = new StringEntity(json);
                // 6. set httpPost Entity
                httpPost.setEntity(se);
                // 7. Set some headers to inform server about the type of the content   
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");
                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPost);







                inputStream = httpResponse.getEntity().getContent();


                BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
                String line = "";
                while((line = bufferedReader.readLine()) != null)
                    result += line;

                inputStream.close();



            } catch (Exception e) {
            }

            // 11. return result
            return result;

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (nDialog.isShowing()) {
                nDialog.dismiss();
            }



            Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();


        }

    }



}
{
   "name":"hima",
   "password":"sample123"
}
回应如下:

{
  "userId": 1,
  "userName": "hima"
}
但是我得到了org.apache.http.client.ClientProtocolException的空白响应。我需要帮助才能找到问题。 日志cat如下所示

07-30 12:41:49.713 31015-31015/?V/GAV4﹕ 螺纹[main,5,main]:连接到服务 07-30 12:41:49.719 31015-31033/? I/GAV4﹕ Thread[GAThread,5,main]:未找到活动数据。 07-30 12:41:49.719 31015-31033/? V/GAV4﹕ 线程[GAThread,5,main]:初始化的GA线程 07-30 12:41:49.878 744-813/? I/ActivityManager﹕ 启动程序31097:com.android.chrome:privileged_process1/u0a34 for service com.android.chrome/org.chromium.content.app.PrivilegedProcessService1 07-30 12:41:49.921 31097-31097/? I/ChildProcessService﹕ 创建新的ChildProcessService pid=31097 07-30 12:41:49.924 744-2781/? I/ActivityManager﹕ Killing 27220:com.google.android.apps.photos/u0a65(形容词15):空的 07-30 12:41:50.053 744-1192/? I/ActivityManager﹕ 杀人30231:com.google.android.apps.gcs/u0a84(形容词15):空#17 07-30 12:41:50.982 744-764/? V/WindowManager﹕ 非基本应用程序:在第6页(共21页)添加窗口{161d5b01 u0登录…} 07-30 12:41:51.853 30701-31115/com.example.arunraj.locationtracker I/System.out﹕ 例外nnnnnnnnnnnnnorg.apache.http.client.ClientProtocolException
07-30 12:41:51.881 744-897/? W/InputMethodManagerService﹕ 窗口已聚焦,忽略焦点增益:com.android.internal.view.IInputMethodClient$Stub$Proxy@8173b94attribute=null,token=android.os。BinderProxy@3dcb4c75

我猜你正在吞咽的
doInBackground
代码中有一个异常。尝试打印catch语句中的异常,然后从那里开始。

我尝试执行rest api,但出现错误404,表示未找到用户,我已附加rest客户端的映像


您的URL=”http://safetracker-threetinker.rhcloud.com/api/login“它不起作用。首先检查它。

首先,正如您可能知道的,它已被弃用,请使用

使用从注释中提取的以下json:

{
   "name":"arya",
   "password":"arya123"
}
我们得到一个Http代码302,它通常是对重定向的响应(Http 302临时移动),但似乎您的api已将其重写为Http 302 find,而不是Http 200 Ok。这可能就是为什么会出现ClientProtocolException的原因

因此,为了使事情顺利进行,您只需要处理这个HTTP302,就像处理HTTP200OK一样。修改上述提供的代码,如下所示:

// 8. Handle response
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //success
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    while((line = bufferedReader.readLine()) != null)
        result += line;
    bufferedReader.close();

    Log.d("StackOverFlow", result);
}
瞧!魔法完成了:

07-30 11:25:11.350  27868-29041/com.example.stackoverflowtestapp I/StackOverFlow﹕ POST Response Code :: 302
07-30 11:25:11.350  27868-29041/com.example.stackoverflowtestapp D/StackOverFlow﹕ {"userId":15,"userName":"arya"}
希望有帮助

----------编辑----------


作为补充说明,如果您打算在Android上处理REST API,我建议您查看一下

Pleae suggest Solutions将一些日志放在异常上,并记录httpResponse,这应该会给您一些关于发生了什么的指示。请告诉我您将internet权限放在清单
上,请打印日志。。你可能在你的doInBackground方法中做错了什么。用logcatIt更新的问题确实有效,请检查@RamIndani答案!这是一个POST请求,您没有使用此用户名的用户,或者您的REST api返回错误结果。在处理android客户端中的响应之前,您应该检查Http状态代码。name=“arya”password=“arya123”存在,但响应为blank是的,您是对的。我收到一个异常,名为apache.Http.client.ClientProtocolException。这个例外的原因是什么。
// 8. Handle response
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //success
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    while((line = bufferedReader.readLine()) != null)
        result += line;
    bufferedReader.close();

    Log.d("StackOverFlow", result);
}
07-30 11:25:11.350  27868-29041/com.example.stackoverflowtestapp I/StackOverFlow﹕ POST Response Code :: 302
07-30 11:25:11.350  27868-29041/com.example.stackoverflowtestapp D/StackOverFlow﹕ {"userId":15,"userName":"arya"}