¿Cómo agregar parámetros y cómo obtener cadena? (Java, httpclient 4.x)
-
27-10-2019 - |
Pregunta
Código http get solicitud:
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) {
}
}
¿Cómo obtener una cadena de respuesta?
Y necesito crear una publicación de solicitud, agregar parámetros y redirección automática.
Solución
Puede haber una forma más rápida de hacer esto, pero esto le dará la respuesta como una cadena:
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();
Para crear una solicitud de publicación, uso:
PostMethod post = new PostMethod("http://url.com");
post.addParameter("param1name", "param1value");
O httppost: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
Httpclient debe manejar las redireccionamientos automáticas para usted
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow