【发布时间】:2019-06-25 14:06:20
【问题描述】:
我正在使用 openweathermap.org 中的 api 构建一个天气应用程序,当我运行该程序时它显示一个错误。如何解决这个问题?
我在 openweathermap.org 上创建了一个帐户来创建 api 密钥并使用 url="https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=2ee7238c0e02a5b1efef8418a075c72c"
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection conn=null;
try {
String result="";
url=new URL(urls[0]);
conn=(HttpURLConnection) url.openConnection();
conn.connect();
InputStream is=conn.getInputStream();
InputStreamReader reader=new InputStreamReader(is);
int data=reader.read();
while(data!=-1){
char current=(char)data;
result=current+result;
data=reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json=new JSONObject(result);
String weatherInfo=json.getString("weather");
Log.i("Contents ",weatherInfo);
JSONArray arr=new JSONArray(weatherInfo);
for(int i=0;i<arr.length();i++){
JSONObject jsonPart=arr.getJSONObject(i);
Log.i("main",jsonPart.getString("main"));
Log.i("decription",jsonPart.getString("description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task=new DownloadTask();
try {
task.execute("https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=2ee7238c0e02a5b1efef8418a075c72c").get();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出是:
org.json.JSONException: Expected literal value at character 0 of }002:"doc","nodnoL":"eman",3473462:"di",0063:"enozemit",}2114941651:"tesnus",8424341651:"esirnus","BG":"yrtnuoc",1900.0:"egassem",4141:"di",1:"epyt"{:"sys",1880741651:"td",}09:"lla"{:"sduolc",}033:"ged",1.3:"deeps"{:"dniw",00001:"ytilibisiv",}62.992:"xam_pmet",51.092:"nim_pmet",37:"ytidimuh",8101:"erusserp",24.592:"pmet"{:"niam","snoitats":"esab",]}"d01":"noci","niar thgil":"noitpircsed","niaR":"niam",005:"di"{[:"rehtaew",}15.15:"tal",31.0-:"nol"{:"drooc"{
【问题讨论】: