2011-08-22 178 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

尝试它没有运气。没有输出,也没有例外。有关代码,请参阅编辑的帖子。 –