如何立即获得JSON响应

时间:2019-02-08 10:57:42

标签: android json

反正有即时获得json响应的机会,这是我第一次研究json,对我的语法和代码感到抱歉。

我试图在执行时设置延迟,我想不使用处理程序而寻找另一种方法。postdelay我想要无延迟地获取数据。

        @Override
        protected String doInBackground(String... args) {
           un = args[0];
           up = args[1];
            try {
                StringBuilder JSON_DATA = new StringBuilder();
                URL url = new URL(JSON_URL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data_string = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(un,"UTF-8")+"&"+
                        URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(up,"UTF-8");
                        bufferedWriter.write(data_string);
                        bufferedWriter.flush();
                        bufferedWriter.close();
                        outputStream.close();
                InputStream  in = httpURLConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                while ((JSON_STRING = reader.readLine())!=null) {
                    JSON_DATA.append(JSON_STRING).append("\n");
                }
                String x = JSON_DATA.toString().trim();
                if(x.equals("1"))
                {
                    return null;
                }
                else
                {
                return JSON_DATA.toString().trim();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;            
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {

            json_string = result;
        }
    }
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    getActionBar().hide(); 
    setContentView(R.layout.activity_main);
    B1 = (Button)findViewById(R.id.btnloginok);
    t1 = (TextView)findViewById(R.id.name);
    t2 = (TextView)findViewById(R.id.pname);
    //new BackgroundTask().execute();
    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

这就是我试图获得答复的原因

public void login(View v)
{
    String uname = un.getText().toString();
    String upass = pass.getText().toString();
    BackgroundTask backgroundTask = new BackgroundTask();
    backgroundTask.execute(uname,upass);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // Do something after 5s = 5000ms
            if(json_string==null)
            {
                Toast.makeText(getApplicationContext(), "Login Failed Try Again..", Toast.LENGTH_LONG).show();

            }
            else
            {
                //Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
                Intent intent = new Intent(MainActivity.this,intro.class);
                intent.putExtra("json_data", json_string);
                startActivity(intent);

            }
        }
    }, 4000);       
}

}

有时我会得到空响应。

1 个答案:

答案 0 :(得分:1)

请在https://developer.android.com/reference/android/os/AsyncTask阅读有关AsyncTask的信息

使用Handler等待网络呼叫响应不是正确的方法。现在,您正在等待4秒钟,如果响应在5时返回,则json字符串中将为null。

当您使用AsyncTask进行网络通话时,onPostExecute是接收回数据时的回调。

您应该更改onPostExecute中的活动。如下更改login方法

public void login(View v)
{
    String uname = un.getText().toString();
    String upass = pass.getText().toString();
    BackgroundTask backgroundTask = new BackgroundTask();
    backgroundTask.execute(uname,upass);
}

创建这样的新方法

private void onLoginResponse(String json){
    if(json==null)
    {
        Toast.makeText(getApplicationContext(), "Login Failed Try Again..", Toast.LENGTH_LONG).show();
    }
    else
    {
        //Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
        Intent intent = new Intent(MainActivity.this,intro.class);
        intent.putExtra("json_data", json);
        startActivity(intent);
    }
}

现在像这样在onPostExecute中调用此方法

 @Override
 protected void onPostExecute(String result) {
    json_string = result;
    onLoginResponse(json_string);
 }