由于 HttpClient 已经不被采用,我在学习 11.3.2 节的时候,就尝试用 HttpURLConnection 来代替。
以下是我用 HttpURLConnection 重写了的代码:
package com.hultron.locationtest;
public class MainActivity extends AppCompatActivity {
public static final int SHOW_LOCATION = 0;
......
private void showLocation(final Location location) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//组装反向地理编码的接口地址
//使用 HttpURLConnection 替换 HttpClient
URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ location.getLatitude() + "," + location.getLongitude() + "&sensor=false");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//在请求中指定语言,保证服务器会返回中文数据
connection.setRequestProperty("Accept-Language","zh-CN");
InputStream in = connection.getInputStream();
// 下面对获取的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
JSONObject jsonObject = new JSONObject(response.toString());
//Log.d("MainActivity",response.toString());
//获取 results 节点下的位置信息
JSONArray resultArray = jsonObject.getJSONArray("results");
if (resultArray.length() > 0) {
JSONObject subObject = resultArray.getJSONObject(0);
//取出格式化后的位置信息
String address = subObject.getString("formatted_address");
Message message = new Message();
message.what = SHOW_LOCATION;
//将服务器返回的结果存放到 message 中
message.obj = address;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_LOCATION:
String currentPosition = (String) msg.obj;
positionTextView.setText(currentPosition);
break;
default:
break;
}
}
};
}
ps.我昨天反复运行了三次这段代码,都成功得到了当前的位置信息,然后刚才为了测试,又运行了一遍,却失败了。反复检查后,发现没毛病。。。我想,可能是墙的问题。。。