我能够将值从android注册到服务器,但无法获得JSon响应 [英] I am able to register the values to server from android but not able to get JSon response

查看:99
本文介绍了我能够将值从android注册到服务器,但无法获得JSon响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将值从android注册到服务器,但无法获得JSon响应. 这是我的代码,应该在userareaActivity中显示输出:

I am able to register the values to server from android but not able to get JSon response. Heres my code ,it was supposed to show output in userareaActivity :

我的activity_main.xml

my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="twin.com.heyjson.MainActivity">


    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginEnd="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="8dp"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">


        <TextView
            android:id="@+id/textView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Email" />

        <EditText
            android:id="@+id/et1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
             />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Contact number" />

        <EditText
            android:id="@+id/et2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
           />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="password" />

        <EditText
            android:id="@+id/et3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
             />

        <Button
            android:id="@+id/btn1"
            android:layout_marginTop="40sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register"
            android:onClick="hit"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

主要活动:

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
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 java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.ResponseCache;


import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    EditText emailview, numberview, pwview;
    Button registerview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        emailview = (EditText) findViewById(R.id.et1);
        numberview = (EditText) findViewById(R.id.et2);
        pwview = (EditText) findViewById(R.id.et3);
        registerview = (Button) findViewById(R.id.btn1);
    }

    public void hit(View v) {
        String email = emailview.getText().toString();
        String contact = numberview.getText().toString();
        String pw = pwview.getText().toString();
        JSONObject a = new JSONObject();

        try {
            a.put("mail", email);
            a.put("num", contact);
            a.put("pass", pw);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (a.length() > 0) {
            new SendJsonDataToServer().execute(String.valueOf(a));
        }
    }

    class  SendJsonDataToServer extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            String JsonResponse = null;
            String JsonDATA = params[0];
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL("example.com");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                // is output buffer writter
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
                Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
                writer.write(JsonDATA);
// json data
                writer.close();
                InputStream inputStream = urlConnection.getInputStream();
//input stream
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String inputLine;
                while ((inputLine = reader.readLine()) != null)
                    buffer.append(inputLine + "\n");
                if (buffer.length() == 0) {
                    // Stream was empty. No point in parsing.
                    return null;
                }
                JsonResponse = buffer.toString();
//response data
                Log.i("o/p:", JsonResponse);
                try {
//send to post execute
                    return JsonResponse;
                } catch (Exception e){

                }
                return null;

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("wtf", "Error closing stream", e);
                    }
                }
            }
            return null;
        }




    @Override
    protected void onPostExecute(String s) {
        Log.i("Here it is:",s);
        Log.e("Here it is:",s);
        try {
            JSONObject jsonResponse = new JSONObject(s);
            int status= jsonResponse.getInt("status");
            String message =jsonResponse.getString("message");

            JSONArray arr = jsonResponse.getJSONArray("data");

                if ( status==1){
                    for (int i=0;i<arr.length();i++) {
                        JSONObject lol = arr.getJSONObject(i);

                        String token = lol.getString("token");
                        String email = lol.getString("email");


                        Intent intent = new Intent(MainActivity.this, UserAreaActivity.class);
                        intent.putExtra("message", message);
                        intent.putExtra("token", token);
                        intent.putExtra("email", email);

                        startActivity(intent);


                    }}


            else {

                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Registration failed").setNegativeButton("retry",null)
                        .create()
                        .show();
            }




        } catch (JSONException e) {

            e.printStackTrace();
        }



    }}
}

Activity_user_area.xml:

Activity_user_area.xml :

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="twin.com.heyjson.UserAreaActivity">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            tools:layout_constraintTop_creator="1"
            tools:layout_constraintRight_creator="1"
            tools:layout_constraintBottom_creator="1"
            android:layout_marginStart="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginEnd="8dp"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="8dp"
            tools:layout_constraintLeft_creator="1"
            android:layout_marginBottom="8dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintVertical_bias="1.0">


            <TextView
                android:id="@+id/tv1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Message" />

            <TextView
                android:id="@+id/tv2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="token" />

            <TextView
                android:id="@+id/tv3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="email" />
        </LinearLayout>
    </android.support.constraint.ConstraintLayout>


UserAreaActivity :



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

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


public class UserAreaActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_area);
        setContentView(R.layout.activity_user_area);
        final TextView tar =(TextView)findViewById(R.id.tv1);
        final TextView zar =(TextView)findViewById(R.id.tv2);
        final TextView par =(TextView)findViewById(R.id.tv3);



        Intent intent=getIntent();
        String message=intent.getStringExtra("message");
        String token =intent.getStringExtra("token");
        String email=intent.getStringExtra("email");



        tar.setText(message);
        zar.setText(token);
        par.setText(email);



    }
}

我的清单文件:

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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=".UserAreaActivity"></activity>
    </application>

</manifest>

推荐答案

您用于发布数据的方法是正确的,但是您正在创建具有POST属性的HttpUrlConnection,该连接旨在将您的数据发布到某些特定的Web服务端点,该端点接受数据作为POST参数.因此,如何使用相同的HttpUrlConnection从服务器获取数据.在这种情况下,您需要使用旨在从服务器获取数据的不同URL创建一个不同的HttpUrlConnection.理想情况下,您不应该使用相同的AsyncTask进行POST,而来自Web服务器的GET数据对POST和GET使用不同的数据.

The method you are using to post data is right but you are creating an HttpUrlConnection with POST properties and this connection is intended to POST your data to some specific web service endpoint, which accept data as POST parameters. So how can you use same HttpUrlConnection to get data from server. In that case you need to create a different HttpUrlConnection with different URL that is intended to get data from server. Ideally you shouldn't use same AsyncTask to POST and GET data from web server use different for both POST and GET.

这篇关于我能够将值从android注册到服务器,但无法获得JSon响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆