0

代码Http获取请求:

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) {
        }
    }

如何得到响应字符串?

我需要创建请求 POST,添加参数和自动重定向。

4

1 回答 1

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();

要创建发布请求,请使用:

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

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

HttpClient 应该为您处理自动重定向

于 2011-04-30T16:10:03.967 回答