Wednesday, 7 August 2013

Java sending request multipart/form data

Java sending request multipart/form data

I'm trying to send an HTTP request to a web using POST, I want to mimic
the behavior of this form and get the resulting HTML code.
<form action="http://www.myweb.com/index.php?route=account/login"
method="post" enctype="multipart/form-data">
<div class="content">
<p>Ya soy cliente</p>
<b>Dirección e-mail:</b><br>
<input type="text" name="email" value="">
<br>
<br>
<b>Contraseña:</b><br>
<input type="password" name="password" value="">
<br>
<a
href="http://www.myweb.com/index.php?route=account/forgotten">Contraseña
olvidada</a><br>
<br>
<input type="submit" value="Entrar" class="button">
</div>
</form>
So far, I've used HttpClient from apache, but doesn't work. I get the next
message:
executing request POST http://www.myweb.com/index.php?route=account/login
HTTP/1.1
HTTP/1.1
200 OK Response content length: -1
HTTP/1.1 200 OK Response content length: -1
org.apache.http.conn.EofSensorInputStream@47cdbe2
The code:
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://myweb.com/" +
"index.php?route=account/login");
StringBody email = new StringBody("myemail@email.com");
StringBody pass = new StringBody("mypass");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("email", email);
reqEntity.addPart("password", pass);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " +
resEntity.getContentLength());
System.out.println(resEntity.getContent());
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch
(Exception ignore) {}
}
Any idea how to get this working? Thanks

No comments:

Post a Comment