2017-09-05 230 views
0

我試圖使用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響應代碼。我試圖瀏覽器創建的網址,它的工作。它在我的模擬器中不起作用。

我該如何解決這個問題。謝謝

+1

這是一個內部服務器錯誤,它可能是服務器的錯誤。 –

+0

但我可以使用瀏覽器訪問相同的網址 –

+0

你有沒有使用過OpenWeatherMap API密鑰? –

回答

0

500 Internal Server Error

服務器遇到阻止它 完成請求的意外情況。

它可能是SERVER錯誤。這錯誤只能通過修復到Web服務器來解決。

+1

感謝您的回覆。但我可以使用瀏覽器訪問相同的網址 –

+1

如果您可以使用瀏覽器訪問相同的網址,請確保將正確的參數和標題添加到您的請求中。這是自服務器端錯誤以來所能做的。 –

+0

@MudithaHasanka面臨問題了嗎? –

相關問題