Welcome to Dream.In.Code
Become a Java Expert!

Join 150,068 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,788 people online right now. Registration is fast and FREE... Join Now!




Sending POST request to a url

 
Reply to this topicStart new topic

Sending POST request to a url

Swetadri
3 Jun, 2008 - 11:41 PM
Post #1

New D.I.C Head
*

Joined: 22 Nov, 2007
Posts: 8


My Contributions
HI all, I want to get content of a user's google-reader account using username and password. Because I want to collect rssfeeds of that particular user and want to store in my database.I have got java code to get content of a normal url like http://yahoo.com..But how to send POST request to google reader internal page?Is there any java code to do that? Following is the code I have got for getting html content of a normal webpage.
CODE

* Get a web file.
*/
public final class WebFile {
// Saved response.
private java.util.Map<String,java.util.List<String>> responseHeader = null;
private java.net.URL responseURL = null;
private int responseCode = -1;
private String MIMEtype = null;
private String charset = null;
private Object content = null;

/** Open a web file. */
public WebFile( String urlString )
throws java.net.MalformedURLException, java.io.IOException {
// Open a URL connection.
final java.net.URL url = new java.net.URL( urlString );
final java.net.URLConnection uconn = url.openConnection( );
if ( !(uconn instanceof java.net.HttpURLConnection) )
throw new java.lang.IllegalArgumentException(
"URL protocol must be HTTP." );
final java.net.HttpURLConnection conn =
(java.net.HttpURLConnection)uconn;

// Set up a request.
conn.setConnectTimeout( 10000 ); // 10 sec
conn.setReadTimeout( 10000 ); // 10 sec
conn.setInstanceFollowRedirects( true );
conn.setRequestProperty( "User-agent", "spider" );

// Send the request.
conn.connect( );

// Get the response.
responseHeader = conn.getHeaderFields( );
responseCode = conn.getResponseCode( );
responseURL = conn.getURL( );
final int length = conn.getContentLength( );
final String type = conn.getContentType( );
if ( type != null ) {
final String[] parts = type.split( ";" );
MIMEtype = parts[0].trim( );
for ( int i = 1; i < parts.length && charset == null; i++ ) {
final String t = parts[i].trim( );
final int index = t.toLowerCase( ).indexOf( "charset=" );
if ( index != -1 )
charset = t.substring( index+8 );
}
}

// Get the content.
final java.io.InputStream stream = conn.getErrorStream( );
if ( stream != null )
content = readStream( length, stream );
else if ( (content = conn.getContent( )) != null &&
content instanceof java.io.InputStream )
content = readStream( length, (java.io.InputStream)content );
conn.disconnect( );
}

/** Read stream bytes and transcode. */
private Object readStream( int length, java.io.InputStream stream )
throws java.io.IOException {
final int buflen = Math.max( 1024, Math.max( length, stream.available() ) );
byte[] buf = new byte[buflen];;
byte[] bytes = null;

for ( int nRead = stream.read(buf); nRead != -1; nRead = stream.read(buf) ) {
if ( bytes == null ) {
bytes = buf;
buf = new byte[buflen];
continue;
}
final byte[] newBytes = new byte[ bytes.length + nRead ];
System.arraycopy( bytes, 0, newBytes, 0, bytes.length );
System.arraycopy( buf, 0, newBytes, bytes.length, nRead );
bytes = newBytes;
}

if ( charset == null )
return bytes;
try {
return new String( bytes, charset );
}
catch ( java.io.UnsupportedEncodingException e ) { }
return bytes;
}

/** Get the content. */
public Object getContent( ) {
return content;
}

/** Get the response code. */
public int getResponseCode( ) {
return responseCode;
}

/** Get the response header. */
public java.util.Map<String,java.util.List<String>> getHeaderFields( ) {
return responseHeader;
}

/** Get the URL of the received page. */
public java.net.URL getURL( ) {
return responseURL;
}

/** Get the MIME type. */
public String getMIMEType( ) {
return MIMEtype;
}
}
/*Main Class calling previous class
class Web
{
public static void main(String[] args)
{
try
{
WebFile file = new WebFile( "http://yahoo.com" );
String MIME = file.getMIMEType( );
Object content = file.getContent( );
if ( MIME.equals( "text/html" ) && content instanceof String )
{
String html = (String)content;
System.out.println(html);

}
}
catch(Exception e)
{
e.printStackTrace(System.out);
}
}
}

[b]
Thanx in advance.I want help urgently..Its needed for my Project..My mail-id is swetadri.iitm@gmail.com...Please mail me
User is offlineProfile CardPM
+Quote Post

lordms12
RE: Sending POST Request To A Url
4 Jun, 2008 - 01:15 AM
Post #2

D.I.C Regular
Group Icon

Joined: 16 Feb, 2008
Posts: 322



Thanked: 17 times
Dream Kudos: 225
My Contributions
No need to write down your mail having conversion here will be more helpful to you and everyone.

Try the following code if you want to POST

CODE
HttpConnection hc = null;
InputStream in = null;
OutputStream out = null;
try {
  String message = "Your Message";
  hc = (HttpConnection)Connector.open(url);//TODO define URL
  hc.setRequestMethod(HttpConnection.POST);
  out = hc.openOutputStream();
  out.write(message.getBytes());
  in = hc.openInputStream();
  int length = (int)hc.getLength();
  byte[] data = new byte[length];
  in.read(data);
  String response = new String(data);//Here is the response
}
catch (IOException ioe) {
}
finally {
  try {
    if (out != null) out.close();
    if (in != null) in.close();
    if (hc != null) hc.close();
  }
  catch (IOException ioe) {}
}

User is offlineProfile CardPM
+Quote Post

1lacca
RE: Sending POST Request To A Url
4 Jun, 2008 - 01:18 AM
Post #3

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 12 times
My Contributions
Check this
User is offlineProfile CardPM
+Quote Post

Swetadri
RE: Sending POST Request To A Url
4 Jun, 2008 - 03:35 AM
Post #4

New D.I.C Head
*

Joined: 22 Nov, 2007
Posts: 8


My Contributions
Dear 1lacca,
I have gone through ur link.But its doing same thing which my code is doing.only ur code is much smaller.I want to pass parameters like username and password to a url.let me clear.Suppose I have a amail id.So, I want to access my inbox via a java code providing username and password.Is it possible?giving a url and getting its content in html format is not a problem.I want to know, how to send POST request to that url which shos my inbox.Got it, na?Any solution?
Thanx in advance
User is offlineProfile CardPM
+Quote Post

1lacca
RE: Sending POST Request To A Url
4 Jun, 2008 - 03:44 AM
Post #5

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 12 times
My Contributions
If you want to access your inbox, it is probably much better to use the POP or IMAP protocol, rather than going through the web interface. There are nice classes and libraries for those.
Anyway, if it is not possible, or you insist on going through HTML, then I don't know what is your problem with the example I've showed you. It sets two post parameters: key1 and key2 to value1 and value2 respectively. You should change key1 to username and key2 to password and value1 and value2 to their values.
User is offlineProfile CardPM
+Quote Post

Swetadri
RE: Sending POST Request To A Url
4 Jun, 2008 - 09:59 PM
Post #6

New D.I.C Head
*

Joined: 22 Nov, 2007
Posts: 8


My Contributions
Dear lordms12,
I have gone through ur link.But its doing same thing which my code is doing.only ur code is much smaller.I want to pass parameters like username and password to a url.let me clear.Suppose I have a amail id.So, I want to access my inbox via a java code providing username and password.Is it possible?giving a url and getting its content in html format is not a problem.I want to know, how to send POST request to that url which shos my inbox.Got it, na?Any solution?
Thanx in advance
User is offlineProfile CardPM
+Quote Post

1lacca
RE: Sending POST Request To A Url
5 Jun, 2008 - 01:45 AM
Post #7

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 12 times
My Contributions
sigh.......
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/8/09 10:52PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month