Code Http get request:
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 :(得分: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应该为您处理自动重定向