у меня есть php-файл в моей ссылке на хостинг-аккаунт —http://www.example.com/hello.php
у меня есть простой код строки в файле hello.php.
Я пытаюсь получить текст «Hello» из файла php при нажатии кнопки в Android и отобразить его в textView.
Можно ли это сделать? Если приведите несколько примеров. Так как я не разрабатывал никаких приложений для Android на основе веб-соединений, я понятия не имею, о чем это.
Делать это должно быть довольно просто:
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();
}
}
Вы можете вернуть строку JSON или все, что вам нужно в вашем коде PHP.
Вы можете узнать больше о создании HTTP-соединений в Android Вот и всегда не забывайте делать это в фоновом режиме, чтобы избежать NetworkOnMainThread исключения.
Следующий код предназначен как для 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("[email protected]", "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();
// }
}}