2012-01-28 83 views
0

我有這樣的代碼在一個普通的Java類和Android實現..HttpURLConnection的Java的X的Android

public static String getURLPage(String urlString){ 
    URL url; 
    String ret = ""; 
    try { 
     url = new URL(urlString); 

     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
     InputStream response = urlConnection.getInputStream(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       response)); 
     for (String line; (line = reader.readLine()) != null;) { 
      ret += line; 
     } 
     reader.close(); 
     return ret; 
    } catch (Exception e) { 

     return e.getLocalizedMessage(); 
    } 
} 

的代碼在Java中返回正確的頁面,但在Android的返回錯誤代碼403 ...

我試圖設置User-Agent,但沒有任何變化。

問題是什麼?

+0

403意味着服務器拒絕你的repquest('禁止')。查看標題並檢查服務器配置,如果它不允許某些標題。 – 2012-01-28 14:25:09

+0

提示:當你在string('ret)上進行了很多連接時,你應該使用['StringBuilder'](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) '變量),因爲它比'String'快得多。 – Crozin 2012-01-28 14:52:18

+0

如果我沒有訪問服務器配置,我是否需要檢查允許的標題? – lucas 2012-01-28 15:13:18

回答

-1

//編輯(對不起,我讀了403錯誤第一次)

從您的問題分開與403錯誤,你可以使用Apache HTTP library,包含在Android系統。你有更好的API比java.net.HttpURLConnection中

下面是一個例子

// imports from org.apache.http (http://hc.apache.org) 
    import org.apache.http.params.HttpConnectionParams; 
    import org.apache.http.params.HttpParams; 
    import org.apache.http.util.EntityUtils; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.client.methods.HttpGet; 
    import org.apache.http.HttpStatus; 

    int TIMEOUT = 2000; 
    String url= "http://your-url.com; 
    HttpParams httpParameters = new BasicHttpParams(); 
    // Set the timeout in milliseconds until a connection is established. 
    HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT); 
    HttpClient hc = new DefaultHttpClient(httpParameters); 

    // which HTTP request: GET or POST ? 
    //HttpPost post = new HttpPost(url); 
    HttpGet get = new HttpGet(url); 

    HttpResponse rp = hc.execute(get); 
    // example to show the result as a string 
    String resultAsString= EntityUtils.toString(rp.getEntity()); 

這不直接幫助,但彩旗就在他的評論。當它工作時(使用java)你應該查看頭文件,並在使用android時比較它們。 你用這個命令得到的參數:

HttpResponse rp = hc.execute(get); 
    // compare the headerParams 
    Header[] requestHeader = get.getAllHeaders(); 
    Header[] responseHeader = rp.getAllHeaders(); 
+0

Thios給出了Erro代碼403 ...我設置了User-Agent = MOzilla仍然不起作用 – lucas 2012-01-28 15:01:28

+0

我編輯我的答案並告訴你如何查找標頭 – timaschew 2012-01-28 17:59:57

+0

好的tnx我會嘗試 – lucas 2012-01-28 20:22:21