最近在学习《第一行代码》第十四章开发酷欧天气,在获取必应的每日一图时遇到了这个问题
Request bing pic with error: failed to connect: getaddrinfo: Temporary failure in name resolution
原因是作者提供的网站guolin.tech/api/bing_pic无法访问,没办法只能自己通过必应官方提供的api来获取图片链接。
官方api:https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
json数据

json数据
图片地址即为"http://cn.bing.com"+url
接下来在Utility中编写函数用来解析返回的json数据并返回图片地址
public static String handleBingPicResponse(String response){
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("images");
JSONObject jsonObject1=jsonArray.getJSONObject(0);
String url=jsonObject1.getString("url");
String bingPic="http://cn.bing.com"+url;
return bingPic;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
接下来简单修改一下原来的loadBingPic()函数即可
private void loadBingPic() {
String requestBingPic="https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String bingPicResponse=response.body().string();
String bingPic=Utility.handleBingPicResponse(bingPicResponse);
Log.d("jzh", "onResponse: "+bingPic);
SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic",bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
});
}