【发布时间】:2015-07-31 01:35:30
【问题描述】:
背景: 我是android编程的新手。我想简单地向本地服务器发出一个 http get 请求。
我想向这个请求传递一个名称作为参数,并希望在 json 中获得返回。这个问题我无法在主线程上执行。我该怎么做?
这是我尝试过的:
主类:
itemsAdapter.add(get.getName(device.getName()));
同一文件中的单独类:
private class httpGet extends AsyncTask<Editable, Void, Integer> {
protected String doInBackground(Editable... params) {
Editable editable = params[0];
return getName(editable.toString());
}
final String getName(String btName) {
HttpResponse response = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://192.168.1.105/getName.php?q=" + btName);
request.setURI(website);
response = client.execute(request);
// Convert String to json object
JSONObject json = new JSONObject(response.toString());
// get LL json object
JSONObject json_Name = json.getJSONObject("Name");
// get value from LL Json Object
name = json_Name.getString("value"); //<< get value here
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
// Do something to recover ... or kill the app.
}
return result;
}
protected void onPostExecute(Integer result) {
// here you have the result
}
我不确定这是否是完成这项任务的好方法。我也不知道该怎么称呼它。
【问题讨论】:
标签: java android multithreading http-get