2014-04-17 108 views
0

我無法通過Android應用程序調用API。 我使用本網站的幫助:http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSONAPI的HttpClient問題:錯誤代碼404

當我嘗試將URL更改爲,我想使用的API,我得到得到一個:「服務器的狀態代碼:迴應:404」。

這是我第一次使用AsyncTask,所以我希望我做得正確。這裏是我的AsyncTask類:

private class PostFetcher extends AsyncTask<Void, Void, String> { 
    private static final String TAG = "PostFetcher"; 
    public String SERVER_URL = "https://bitpay.com/api/rates"; 

    @Override 
    protected String doInBackground(Void... params) { 
     try { 
      //Create an HTTP client 
      HttpClient client = new DefaultHttpClient(); 
      HttpPost post = new HttpPost(SERVER_URL); 

      //Perform the request and check the status code 
      HttpResponse response = client.execute(post); 
      StatusLine statusLine = response.getStatusLine(); 
      if(statusLine.getStatusCode() == 200) { 
       HttpEntity entity = response.getEntity(); 
       InputStream content = entity.getContent(); 

       try { 
        //Read the server response and attempt to parse it as JSON 
        Reader reader = new InputStreamReader(content); 

        Log.i(TAG, "Connected"); 

        content.close(); 

       } catch (Exception ex) { 
        Log.e(TAG, "Failed to parse JSON due to: " + ex); 
        failedLoadingPosts(); 
       } 
      } else { 
       Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode()); 
       failedLoadingPosts(); 
      } 
     } catch(Exception ex) { 
      Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
      failedLoadingPosts(); 
     } 
     return null; 
    } 
} 

而上的onCreate,我呼籲: PostFetcher提取器=新PostFetcher(); fetcher.execute();

任何想法,爲什麼我得到404錯誤代碼,即使網站功能?謝謝!

+0

也請消耗您的httpendity。 MALLOC不會收集它! – bluewhile

回答

1

也許你需要使用HTTP GET代替POST。

+0

呃!如此簡單的事情會如此令人頭痛!謝謝!它能夠通過。 – AlwaysLearning

0

你設置權限

 <uses-permission android:name="android.permission.INTERNET" /> 

,並嘗試這種方式

class PostFetcher extends AsyncTask<Void, Void, String> { 
private static final String TAG = "PostFetcher"; 
public String SERVER_URL = "https://bitpay.com/api/rates"; 

@Override 
protected String doInBackground(Void... params) { 
    try { 
     String result =""; 

     URL myUrl = new URL(SERVER_URL); 

     HttpURLConnection conn = (HttpURLConnection) myUrl 
       .openConnection(); 

     //conn.setRequestMethod("POST"); //if you need set POST 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     conn.connect(); 

     InputStream is = conn.getInputStream(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "UTF-8"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String lineJSON = null; 
     while ((lineJSON = reader.readLine()) != null) { 
      sb.append(lineJSON + "\n"); 
     } 
     result = sb.toString(); 
     Log.d(TAG, result); 


    } catch(Exception ex) { 
     Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
     //failedLoadingPosts(); 
    } 
    return null; 
} 
} 

好運!