2017-06-21 47 views
0

我能值从机器人,但没能获得JSON响应注册到服务器的服务器。 继承人我的代码,它应该表现出userareaActivity输出:我能值寄存器从Android,但没能获得JSON响应

我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:

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

回答

0

之前盲目读取输入流,尝试检查与响应状态,

int code = urlConnection.getResponseCode() 

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

读取数据干杯!

0

您使用发布数据的方法是正确的,但要创建一个使用POST性质的HttpURLConnection类和这个连接是为了你的POST数据到一些特定的Web服务端点,它接受的数据作为POST参数。那么如何使用相同的HttpUrlConnection从服务器获取数据。在这种情况下,您需要创建一个具有不同URL的不同HttpUrlConnection,以便从服务器获取数据。理想情况下,您不应该使用相同的AsyncTask来POST和从Web服务器的GET数据使用不同的POST和GET。

+0

你能否解释多一点PLZ?就像从第一的AsyncTask我应该从onpostexceute方法调用第二的AsyncTask?是这样的吗?但是,当注册completed.So什么会我声明为地址的新asyntasks网址是什么?再次相同的URL我的服务器自动reponds?我不这样认为新的连接必须被创建。因为说不定就会把它当作一个新的请求再次,当新的请求没有表单提交,发送,服务器不会respond.So看着我的代码u能再次告诉我,什么是错,为什么中号无法取得回应并显示它?Thx为你的努力兄弟:) – Robin10