我能够从android注册到服务器的值,但无法获得JSon响应

时间:2017-06-21 17:06:15

标签: android json

我能够从android注册到服务器但不能获得JSon响应。 继承我的代码,它应该在userareaActivity中显示输出:

my activity_main.xml

element.getAttribute("value")

主要活动:

<?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>

Activity_user_area.xml:

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();
        }



    }}
}

我的清单文件:

    <?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);



    }
}

2 个答案:

答案 0 :(得分:0)

在盲目阅读输入流之前,尝试使用

检查响应状态
int code = urlConnection.getResponseCode()

如果代码是200系列中的任何一个,那么您已成功将数据发布到服务器。根据代码值,从urlConnection.getInputStream()urlConnection.getErrorStream()

中读取数据

干杯!!

答案 1 :(得分:0)

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

相关问题