【发布时间】:2017-11-06 18:16:12
【问题描述】:
我从How can I make a simple HTTP request in MainActivity.java? (Android Studio) 在这里找到了一个简单的HTTP 请求的工作代码,我将在下面发布它(有一些更改,如果我没记错的话,现在必须使用try{} catch{})。但是我想问我如何才能收到内容?我通过以下方式处理代码:
GetUrlContentTask req = new GetUrlContentTask();
req.execute("http://192.168.1.10/?pin=OFF1");
textView3.setText(req.doInBackground("http://192.168.1.10/?pin=OFF1"));
GetUrlContentTask
private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
// String content1 = "";
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
// content1 = content;
}
catch (Exception e) {
e.printStackTrace();
}
// return content1; - returns "", wrong
return "aaa";
//does not work return content;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
}
}
【问题讨论】:
-
你期望什么样的响应——一个json对象?
-
我建议你使用Retrofit
-
@Barns52 我期待纯 HTML 文本。