【问题标题】:Android + PHP connection安卓+PHP连接
【发布时间】:2016-06-04 11:51:32
【问题描述】:
我的托管帐户 url 链接中有一个 php 文件是 --http://www.example.com/hello.php
我在 hello.php 文件中有简单的行代码。
当在Android中按下按钮并将其显示在textView中时,我试图从php文件中获取文本“Hello”。
可以吗?如果给我一些例子。因为我还没有开发任何基于网络连接的安卓应用程序,我不知道这是怎么回事。
【问题讨论】:
标签:
php
android
httpconnection
【解决方案1】:
这样做应该很简单:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
您可以在 PHP 代码中返回 JSON 字符串或任何您需要的内容。
您可以了解有关在 android here 中建立 HTTP 连接的更多信息,并始终记得在后台执行此操作以避免 NetworkOnMainThread 异常。
【解决方案2】:
以下代码适用于 GET 和 POST。
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends Activity {
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//calling POST request
public void sendPostRequest(View View) {
new PostClass(this).execute();
}
public void sendGetRequest(View View) {
new GetClass(this).execute();
}
private class PostClass extends AsyncTask<String, Void, Void> {
private final Context context;
public PostClass(Context c){
this.context = c;
// this.error = status;
// this.type = t;
}
protected void onPreExecute(){
progress= new ProgressDialog(this.context);
progress.setMessage("Loading");
progress.show();
}
@Override
protected Void doInBackground(String... params) {
try {
final TextView outputView = (TextView) findViewById(R.id.showOutput);
//your url goes here
URL url = new URL("http://www.example.com/hello.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// parameters to the url if required
String urlParameters =
"key=" + URLEncoder.encode("a12345", "UTF-8") +
"&username=" + URLEncoder.encode("example@gmail.com", "UTF-8")+
"&password=" +URLEncoder.encode("123456", "UTF-8")+
"&device_id=" +URLEncoder.encode("1", "UTF-8");
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
//get our response here
final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "POST");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
progress.dismiss();
}
}
private class GetClass extends AsyncTask<String, Void, Void> {
private final Context context;
public GetClass(Context c){
this.context = c;
}
protected void onPreExecute(){
progress= new ProgressDialog(this.context);
progress.setMessage("Loading");
progress.show();
}
@Override
protected Void doInBackground(String... params) {
try {
final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL("http://requestb.in/1cs29cy1");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
String urlParameters = "fizz=buzz";
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
final StringBuilder output = new StringBuilder("Request URL " + url);
//output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// protected void onPostExecute() {
// progress.dismiss();
// }
}
}