当您点击网页上的按钮时,浏览器会向指定的 url ( http://91.137.148.13:8000/leds.cgi?led=0
) 发送请求。因此,当用户单击您的 Android 应用程序中的按钮时,您可以向此 url 发送请求。
private class exampleHttpTask extends AsyncTask<Integer, Integer, String> {
public String convertStreamToString(InputStream is, String charset) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, charset));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
protected String doInBackground(Integer... params) {
String r = "";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://91.137.148.13:8000/leds.cgi?led=0");
HttpResponse hr = hc.execute(get);
if(hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream is = hr.getEntity().getContent();
r = convertStreamToString(is, "UTF-8");
} else {
r = "Error";
}
} catch(Exception e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
Log.d("WEB", result);
}
protected void onPreExecute() {
}
}
(代码来自这里)并且当 onClick 事件被触发时,运行
new exampleHttpTask().exec()