2012-04-14 74 views
0

我不太确定它是如何工作的,但我需要做的是使用JSON-RPC进行身份验证,然后请求一个页面。我有这样的代码,以找出是否用户名和密码是正确的,但我不知道如何使用这些信息来请求一个页面..Html,auth。获取Cookie

List<Cookie> cook; 
    public void postData(String method, Object ... params) throws JSONException { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.examp;e.com/json-rpc/"); 

     try { 
      // Add your data 

      String methodandp = "{id:3, method:" + method + ", params:[" + params[0].toString()+ ", " + params[1].toString() + "]}"; 

      StringEntity a = new StringEntity(methodandp); 
      httppost.setEntity(a); 
      Log.i("ClientActivity: request", httppost.getMethod().toString()); 
      Log.i("ClientActivity: request", nameValuePairs.toString()); 


      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 


      Header[] head = response.getAllHeaders(); 

      Log.i("ClientActivity", response.getStatusLine().toString()); 
      String responseString = EntityUtils.toString(response.getEntity()); 
      responseString = responseString.trim(); 
      JSONObject jsonResponse = new JSONObject(responseString); 
      Log.i("ClientActivity", jsonResponse.toString()); 
      String cookie = ""; 

      for(int i = 0; i < head.length; i++){ 
       Log.i("ClientActivity: response", head[i].toString()); 
       if(head[i].toString().contains("Set-Cookie")){ 
        cookie = (head[i].toString()).replace("Set-Cookie: ", ""); 
        cook = ((AbstractHttpClient) httpclient).getCookieStore().getCookies(); 
        if (cook.isEmpty()) { 
         System.out.println("None"); 
        } else { 
         for (int x = 0; x < cook.size(); x++) { 
          Log.i("ClientActivity", "-" + cook.get(x).toString()); 
         } 
        } 
        Log.i("ClientActivity: Cookie", cookie); 
       } 
      } 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
    } 

它回来了成功,并与所有正确的数据,但我不知道如何使用它。

+1

很多代码与从响应中提取cookie并不相关,所以也许你应该首先清理它。现在如果你已经完成了for循环,你通常应该(通常意味着:对cookie字符串执行一个空的检查)在所谓的变量中的cookie。然后,您可以创建一个GET请求,设置一个包含此Cookie的标题,并检索所需的网页。 – Rob 2012-04-14 01:39:41

+0

好的,我已经这样做了,但现在如何获取我刚刚请求的内容? – FabianCook 2012-04-14 02:00:24

+0

你可以尝试澄清你的实际问题吗?你究竟想从这个URL检索的数据做什么?尝试转发到其他页面? – robertvoliva 2012-04-14 03:44:21

回答

1

这实际上很简单,现在我看它,一旦我确认了我已经过身份验证,我可以使用相同的HttpClient(持有cookie)请求其他文件并使用MultipartEntity将文件推送到Web服务器