2017-10-06 87 views
-2

以下是我的代碼,請幫助我,我需要使用post方法用戶名和密碼登錄到網站。我在網上查了一些例子,並使用wiki來做這件事。我將按鈕中的所有內容設置爲點擊,如您所見:如何在Android中編寫POST方法

package com.example.work.try1; 

import android.widget.Button; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.EditText; 
import android.net.Uri; 
import android.content.Intent; 
import android.view.View; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class Launch extends AppCompatActivity { 

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

    final View buttonS = findViewById(R.id.button); 
    buttonS.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      Uri uri = Uri.parse("https://www.navanithiastrolife.com"); 
      Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
      startActivity(intent); 
     } 
    }); 

    Button b = (Button) findViewById(R.id.button2); 
    b.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      EditText e1 = (EditText) findViewById(R.id.editText); 
      String username = e1.getText().toString(); 
      EditText e2 = (EditText) findViewById(R.id.editText3); 
      String password = e2.getText().toString(); 

      OutputStream out = null; 
      try { 

       URL url = new URL("http://iconinfo.tech/mob_app/"); 

       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

       urlConnection.connect(); 

       urlConnection.setRequestMethod("POST"); 
       urlConnection.setRequestProperty("username",username); 
       urlConnection.setRequestProperty("password",password); 
       urlConnection.setDoOutput(true); 

       urlConnection.disconnect(); 

      } catch (Exception e) { 
       System.out.println(e.getMessage()); 
      } 
     } 
    }); 
} 
} 

請協助,確定thx。

+0

只是使用改造 – sushildlh

+0

你需要一個後臺線程的網絡操作 – Raghunandan

+0

https://stackoverflow.com/a/13486223/3635454 – pleft

回答

0

您還可以使用volley library調用API

我希望它有助於你..!

+0

我想發佈到PHP,排氣使用JSON看起來像java? – sadaiyappan

+0

是的,它使用JAVA ..! 你也可以發送POST請求..! –

0

您的請求正在主線程中完成,這是不正確的,因爲它可能會阻塞主線程。對於此背景操作,您必須使用後臺線程,如Volley庫,Retrofit或RoboSpice。要構建POST方法,您必須構建您的文章將包含的數據。例如,在Volley中,您使用了一個關鍵值對方法。

+0

我張貼到PHP不到java,所以我仍然可以使用凌空或JSON?或者我必須使用後? – sadaiyappan