1
請我試着用'如何發送字符串到PHP頁面'的不同教程。 我試過的這一款似乎是學習一些東西的最佳解決方案。 該應用程序編譯沒有錯誤,但在我的設備上似乎沒有向PHP頁面發送任何內容。 我給的權限在AndroidManifest.xml中在PHP頁面上發送字符串的方法
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView content;
EditText fname,email,login,pass;
String Name,Email,Login,Pass;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView)findViewById(R.id.content);
fname =(EditText)findViewById(R.id.name);
email =(EditText)findViewById(R.id.email);
login =(EditText)findViewById(R.id.loginname);
pass =(EditText)findViewById(R.id.password);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
try{
GetText();
}
catch(Exception ex)
{
content.setText("url exeption!");
}
}
});
}
public void GetText() throws UnsupportedEncodingException
{
Name = fname.getText().toString();
Email = email.getText().toString();
Login = login.getText().toString();
Pass = pass.getText().toString();
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(Email, "UTF-8");
data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(Login, "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(Pass, "UTF-8");
String text = "";
BufferedReader reader=null;
// Send data
try
{
URL url = new URL("http://thingsforcoins.com/receive/httppost.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
content.setText(text);
}
}
這個應用程序讀取四個領域的EditText和應sended到PHP頁面巫婆將顯示數據串保存數據。