java如何从网页中获取值并在主类中使用它?安卓应用
我试图在网页上读到一些东西,并将其存储在一个名为“finalresult”的变量中。我阅读了文本,使用了HttpURLConnection,并在AsyncTask的doInBacgorund中实现了这一点
我将向您展示我的代码:
public class MainActivity extends AppCompatActivity {
public String finalresult = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
class MyRemote extends AsyncTask<Void, Void, String> {
URL url;
HttpURLConnection connection = null;
@Override
protected String doInBackground(Void... params) {
try
{
//Create connection
url = new URL("My url bla bla");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
finalresult = response.toString();
} catch (Exception e) {
e.printStackTrace();
} finally
{
if (connection != null) {
connection.disconnect();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
当我想在主活动类中使用“finalresult”变量时,我不能,因为它是空的。我怎样才能在我的主要活动课上得到这个结果
Txh。 顺便说一下,我是初学者
# 1 楼答案
请看一下Android的AsyncTask文档。此外,我不确定是否缺少括号或其他内容,但请注意
MyRemote
类声明不能在onCreate()
方法中之所以
finalResult
变量为空,是因为您从未实际使用过所实现的MyRemote
类所以你需要
在
onCreate()
方法中。另外,请记住,因为这个请求是异步的,所以在onPostExecute()
方法中使用finalResult
变量是有意义的此外,用你使用的方式硬编码URL不是一个好主意
相反,它应该作为参数传递给
execute()
方法。再次,看一下文档,它应该会变得更加清晰