2011-08-22 157 views
0

過去兩個小時,我一直在嘗試向此頁面發出POST請求http://www.halebop.se/butik/byt_behall_nummer/並試圖發送numberToPort。不過,我得到了一堆餅乾和一個302暫時移回。Android上的HTTP POST請求

我想要做的就是發送帶有號碼的POST請求並返回最後一頁。在iOS上,我使用ASIHTTPRequest來處理重定向和Cookie。

的iOS代碼:

NSString *halebopURLString = @"http://www.halebop.se/kontantkort/byt_behall_nummer/#"; 
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:halebopURLString]]; 
[request setPostValue:halebopNumber forKey:@"numberToPort"]; 
[request setPostValue:@"continue" forKey:@"action"]; 
[request setPostValue:@"submit" forKey:@"submit"]; 
[request startSynchronous]; 

我如何做到這一點在Android?

作爲替代,PHP解決方案是可以接受的。

編輯:試過這個,它沒有輸出,也沒有例外。我有互聯網許可。預期結果:發送POST,獲取302和cookie,將cookie從302發送到URL,並返回HTML(使用FireBug檢查),但是我什麼也沒得到。

try { 
     InputStream myInputStream =null; 
     URL url; 
     url = new URL("http://www.halebop.se/kontantkort/byt_behall_nummer/#"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setInstanceFollowRedirects(true); 
     conn.setRequestMethod("POST"); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write("numberToPort="+n+"&action=continue&submit=submit"); 
     wr.flush(); 
     myInputStream = conn.getInputStream(); 
     wr.close(); 

     BufferedReader rd = new BufferedReader(new InputStreamReader(myInputStream), 4096); 
     String line; 
     StringBuilder sbResult = new StringBuilder(); 
     while ((line = rd.readLine()) != null) { 
      sbResult.append(line); 
      Log.d(TAG, "Line "+line); 
     } 
     rd.close(); 
     String contentOfMyInputStream = sbResult.toString(); 
     Log.d(TAG, "Output "+contentOfMyInputStream); 
    } catch (Exception e) { 
     Log.d(TAG,e.getMessage()); 
    } 
+6

什麼您正在嘗試使用要做到這一點Android的代碼? –

+0

太亂了,它是我的第一個Android應用程序。如果我無法得到emboss的建議,將會發布。 –

回答

3

這裏是你如何設置崗位參數:

  HttpPost httpost = new HttpPost(LOGIN_URL); 
    List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
    nvps.add(new BasicNameValuePair("test1","test1")); 
    nvps.add(new BasicNameValuePair("test2", "test2")); 

      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 

    response = getResponse(httpost); 

Here是關於代碼的詳細解釋。

我還解釋如何從你的回答中檢索的HTTP cookies,並將它們設置成請求here

1

如果使用HttpURLConnection類,然後HttpUrlConnection#setFollowRedirects可能是你所追求的。將其設置爲true以使其自動解析重定向。更好地使用setInstanceFollowRedirects(true),因爲從安全角度來看,盲目跟隨重定向(靜態setFollowRedirects會導致什麼)是不被接受的。

+0

聽起來不錯,只要我回到我的箱子就會嘗試。它會堅持不懈,並像ASIHTTPRequest一樣發回所有的cookies? –

+0

還沒有回到我的盒子,但我檢查了關於cookie的文檔。是否正確,我需要的是這兩條線,以便自動爲我處理餅乾? ** CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); ** –

+0

嘗試它沒有運氣。沒有輸出,也沒有例外。有關代碼,請參閱編輯的帖子。 –