2011-04-30 71 views
0

代碼HTTP GET請求:如何添加參數和如何獲得字符串? (Java中,HttpClient的4.X)

HttpClient httpclient = new DefaultHttpClient(); 

    CookieStore cookieStore = new BasicCookieStore(); 

    // Create local HTTP context 
    HttpContext localContext = new BasicHttpContext(); 
    // Bind custom cookie store to the local context 
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 

    HttpGet first = new HttpGet("http://vk.com"); 
    HttpResponse response = httpclient.execute(first, localContext); 

    HttpEntity entity = response.getEntity(); 
    if (entity != null) { 
     InputStream instream = entity.getContent(); 
     int l; 
     byte[] tmp = new byte[2048]; 
     while ((l = instream.read(tmp)) != -1) { 
     } 
    } 

如何獲得性反應STRING?

而我需要創建請求POST,添加參數和自動重定向。

回答

0

有可能做到這一點更快捷的方法,但是這將讓你的反應作爲一個字符串:

 InputStream = response.getEntity().getContent(); 
     StringBuilder sb = new StringBuilder(); 
     BufferedReader r = new BufferedReader(new InputStreamReader(in)); 
     for (String line = r.readLine(); line != null; line = r.readLine()) { 
      sb.append(line); 
     } 
     in.close(); 
     String s = sb.toString(); 

要創建一個POST請求使用:

 PostMethod post = new PostMethod("http://url.com"); 
     post.addParameter("param1name", "param1value"); 

或者HttpPost:http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

HttpClient應該爲你處理自動重定向

+0

謝謝,怎麼crea te POST請求? – Mediator 2011-04-30 16:19:05

+0

如何添加 HttpClient client = new HttpClient(); client.getParams()。setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); ? – Mediator 2011-04-30 17:21:45

+0

嗯,你已經在你的問題...? – 2011-04-30 17:53:03

相關問題