我試圖使用android訪問打開的天氣api。我使用了兩種方法,一種用於創建url,另一種用於獲取http響應。Android HttpUrlConnection返回500
創建網址
public static String API_LINK="http://samples.openweathermap.org/data/2.5/weather";
public static String apiRequest(String lat, String lng){
StringBuilder sb=new StringBuilder();
Uri builtUri = Uri.parse(API_LINK)
.buildUpon()
.appendQueryParameter("lat", lat)
.appendQueryParameter("lon", lng)
.appendQueryParameter("appid", API_KEY)
.build();
sb.append(builtUri.toString());
return sb.toString();
}
Http請求
public String getHTTPData(String urlString){
try {
URL url=new URL(urlString);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
Log.d("Helper", httpURLConnection.getResponseCode()+"");
if(httpURLConnection.getResponseCode()==200){//ok=200
BufferedReader r=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
StringBuilder sb=new StringBuilder();
String line;
while ((line=r.readLine())!=null){
sb.append(line);
stream=sb.toString();
httpURLConnection.disconnect();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
,我用一個的AsyncTask調用此方法在MainActivity
new GetWeather().execute(apiRequest("65.9667","-18.5333"));
但每次我ま時間請求我獲得500個http響應代碼。我試圖瀏覽器創建的網址,它的工作。它在我的模擬器中不起作用。
我該如何解決這個問題。謝謝
這是一個內部服務器錯誤,它可能是服務器的錯誤。 –
但我可以使用瀏覽器訪問相同的網址 –
你有沒有使用過OpenWeatherMap API密鑰? –