Android app, HttpURLConnection GET 方法, AsyncTask get tag 而不是



这是一个简单的应用程序,需要使用GET发送两个数字并读回。

Button btnSaberi;
EditText txtAunos, txtBunos;
TextView txtIspis;
String sturl = "http://xxx.xxx.xx.x/PhpProject1/index.php";
Integer a, b;
HttpURLConnection httpURLConnection;
URL url;
public void posalji(View view){
a = Integer.parseInt(txtAunos.getText().toString());
b = Integer.parseInt(txtBunos.getText().toString());
sturl = sturl+"?a=" + a + "&b=" + b;
new Posalji().execute(sturl);
}
class Posalji extends AsyncTask<String, String, String> {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtIspis.setText("Rezultat je : " + s);
}
@Override
protected String doInBackground(String... strings) {
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
rez = br.readLine();
}
return rez;
}
}
}

使用模拟器。

我已经改变了,现在不是向我显示 php 输出,而是向我显示 html 标签。

"<!DOCTYPE html>"

請移除 txtIspis.setText("Rezultat je : " + br.readLine(((;行来自 AsyncTask doInBackground。在doInBackground中,我们从不像这样更新UI。您可以使用 onPostExecute 来更新文本框值。

请阅读此文档 https://developer.android.com/reference/android/os/AsyncTask

当你调用br.readLine((时;只有一次,它只从BufferedReader读取第一行数据。 要从 BufferedReader 读取所有数据行,您需要使用循环。

更新您的 doInBackground 方法

@Override 
protected String doInBackground(String... params){
String url = params[0];
String result;
try {
URL myUrl = new URL(url);
HttpURLConnection connection =(HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect()
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());      
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
}
return result;   
}

最新更新