2017-01-03 59 views
2

我必須發送HTTP請求(通過Android按鈕)到Java Servlet。通過Android按鈕發送HTTP-POST請求

我被困在那裏,我必須把信息(代碼),它必須包含爲了發送它。

語境:在用戶登錄 - >點擊次數 「允許訪問」 - >發送一個HTTP請求到Java Servlet的(例如192.168.1.1)

注:我只是Android的初學者。

我知道它與「Grant Access」按鈕的ID有關。

AndroidManifest:

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

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

    <application 
     android:name=".FireApp" 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true"> 

     <activity 
      android:name=".MainActivity" 
      android:theme="@style/AppTheme"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN"/> 
       <category android:name="android.intent.category.LAUNCHER"/> 
      </intent-filter> 
     </activity> 

     <activity 
      android:name=".AccountActivity" 
      android:theme="@style/AppTheme" /> 
    </application> 

    </manifest> 

Activity_main_xml:

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:baselineAligned="false"> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="163dp" 
     app:srcCompat="@drawable/snetech" 
     android:id="@+id/imageView" /> 

    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:inputType="textEmailAddress" 
     android:ems="10" 
     android:id="@+id/emailField" 
     android:hint="Email" 
     android:paddingTop="20dp" /> 

    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:inputType="textPassword" 
     android:ems="10" 
     android:id="@+id/passwordField" 
     android:hint="Password" 
     android:fontFamily="sans-serif" 
     android:paddingTop="20dp" /> 

    <Button 
     android:text="Login" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/loginBtn" 
     android:paddingTop="20dp" /> 

</LinearLayout> 

Activity_account(如果用戶登錄成功的):

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout 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:id="@+id/activity_account" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.mertino11.ourapplication.AccountActivity"> 


    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="logout" 
     android:id="@+id/logout" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="16dp" /> 

    <Button 
     android:text="Grant Access" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/grantAccess" 
     android:layout_marginBottom="70dp" 
     android:layout_above="@+id/logout" 
     android:layout_centerHorizontal="true" /> 

    <TextView 
     android:text="Main Menu" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/textView" 
     android:textStyle="normal|bold" 
     android:textSize="30sp" 
     android:textAlignment="center" 
     android:fontFamily="sans-serif" 
     android:textAllCaps="false" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 
</RelativeLayout> 

Java類我用:
AccountActivity

import android.content.Intent; 
    import android.os.Bundle; 
    import android.support.v7.app.AppCompatActivity; 
    import android.view.View; 
    import android.widget.Button; 

    import com.google.firebase.auth.FirebaseAuth; 
    public class AccountActivity extends AppCompatActivity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_account); 

     Button logout=(Button) findViewById(R.id.logout); 
     logout.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       FirebaseAuth.getInstance().signOut(); 
       startActivity(new Intent(AccountActivity.this,MainActivity.class)); 
       finish(); 
      } 
     }); 


    } 


} 

MainActivity:

import android.content.Intent; 
    import android.os.Bundle; 
    import android.support.annotation.NonNull; 
    import android.support.v7.app.AppCompatActivity; 
    import android.text.TextUtils; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.Toast; 

    import com.google.android.gms.tasks.OnCompleteListener; 
    import com.google.android.gms.tasks.Task; 
    import com.google.firebase.auth.AuthResult; 
    import com.google.firebase.auth.FirebaseAuth; 

    public class MainActivity extends AppCompatActivity { 

    private EditText mEmailField; 
    private EditText mPasswordField; 

    private Button mLoginBtn; 

    private FirebaseAuth mAuth; 

    private FirebaseAuth.AuthStateListener mAuthListener; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mAuth = FirebaseAuth.getInstance(); 

     mEmailField = (EditText) findViewById(R.id.emailField); 
     mPasswordField = (EditText) findViewById(R.id.passwordField); 

     mLoginBtn = (Button) findViewById(R.id.loginBtn); 

     mAuthListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 

       if(firebaseAuth.getCurrentUser() != null) { 

        startActivity(new Intent(MainActivity.this, AccountActivity.class)); 

       } 
      } 
     }; 

     mLoginBtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       startSignIn(); 

      } 
     }); 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 

     mAuth.addAuthStateListener(mAuthListener); 
    } 

    private void startSignIn() { 

     String email = mEmailField.getText().toString(); 
     String password = mPasswordField.getText().toString(); 

     if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) { 

      Toast.makeText(MainActivity.this, "Fields are empty!", Toast.LENGTH_LONG).show(); 

     } else { 
      mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { 
       @Override 
       public void onComplete(@NonNull Task<AuthResult> task) { 

        if(!task.isSuccessful()){ 

         Toast.makeText(MainActivity.this, "Sign In Problem!", Toast.LENGTH_LONG).show(); 
        } 
       } 
      }); 
     } 



    } 
} 

FireApp:

import android.app.Application; 

    import com.firebase.client.Firebase; 


    public class FireApp extends Application { 
    @Override 
    public void onCreate() { 
     super.onCreate(); 

    Firebase.setAndroidContext(this); 
    } 
    } 

Login Screen User enters his Main Menu

回答

2

據我瞭解,你想打一個HTTP POST同時按鈕@+id/grantAccess點擊。 首先,您必須在AccountActivity類中添加OnClickListener。就像你爲logout按鈕做的那樣。在onClick方法中,您現在可以發出HTTP請求。因此,您必須創建一個AyncTask,因爲您不允許通過應用程序主線程進行HTTP調用。

public class PostTask extends AsyncTask<Void, Void, Void> { 

    private static final String ENDPOINT = "http://yourendpoint/"; 

    PostTask() { 
      //add here your variables that you need 
    } 

    @Override 
    protected void doInBackground(Void... params) { 
     this.doPost(); 
    } 

    @Override 
    protected void onPostExecute() { 
     //do what you want when you are finished 
    } 

    private void doPost(){ 
     final RestTemplate restTemplate = new RestTemplate(); 
     final RequestObject request = new RequestObject(); 

     //parse the request to a format what is used by your endpoint (json, xml,..) 
     HttpEntity<String> entity = new HttpEntity<String>(objectToString(request), createHeaders(authResp)); 
     final HttpEntity<String> response = restTemplate.exchange(ENDPOINT, HttpMethod.POST, entity, String.class); 
    } 
} 

在你onClick方法創建PostTask的實例有:

new PostTask().execute((Void) null); 

就像tudor07說,你可以使用各種HTTP客戶端框架。在這種情況下,我使用Spring for Android(http://projects.spring.io/spring-android/)。在顯示的鏈接中還有一個關於如何將這個庫添加到你的項目的描述。有關異步處理的更多詳細信息,請訪問https://developer.android.com/reference/android/os/AsyncTask.html

1

要能溝通,你需要一個HTTP客戶端框架,可以在您指定的網址,並用一個HTTP方法和參數/體指定讓HTTP請求HTTP低谷。

Android的一個非常流行的框架是Retrofit。 改裝將允許您使用任何您想要的參數進行POST調用。

看看如何設置改造,以及如何創建自己的頁面上的POST電話:https://square.github.io/retrofit/