• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HTTP request 'GET' example

 
Gerry Morris
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to find a good example of how to perform an HTTP 'GET' request in order to send a URI to a remote host and then to retrieve the results. I am very new to the java arena and am having trouble tracking down a good example. Any help would be greatly appreciated for a frustrated newbie!
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suggest you use HttpURLConnection. After a google search, I found this tutorial that might help get you started. Feel free to use google to find what else is available.

Layne
 
Daniel Prene
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not quite sure what you're asking about... Like a servlet with a get request from a form?
[ September 08, 2005: Message edited by: Daniel Prene ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HttpURLConnection is probably the "right" way to do it. I have done it with a simple URL and getInputStream(). See if the JavaDoc on URL or HttpURLConnection makes sense.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel makes a good point. There might be other ways to do this if you are writing a servlet instead of a desktop application. Perhaps you can provide more information about what kind of program you are writing.

Layne
 
Gerry Morris
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing a class to be used by a larger app. My class will be an intermediate step in the process. I will be passed data, which in turn I will pass by HTTP request to a remote machine. I will then gather the response and pass it back to the calling entity.

Does that help?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So did you look at the links I provided above? Did they help at all?

Layne
 
Gerry Morris
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A little....I did end up using HttpURLConnection and think I have basically headed in the right direction. I am needing to use basic authentication for my connection, however despite using the example that I found, I still keep getting a 401 error. Here is my code. Any suggestions are appreciated:

import java.io.*;
import java.net.*;
import java.security.Principal;
import java.util.*;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;


public class OAM
{
public static void main(String[] args)
{
String addr = "http://www.some-url.com";
String username = "username";
String password = "password";
try{
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String encoding = new sun.misc.BASE64Encoder().encode("username assword".getBytes());
conn.setRequestProperty ("Authorization", "Basic " + encoding);
conn.setRequestMethod("GET");

conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String text = reader.readLine();
System.out.println(text);

conn.disconnect();
}catch(IOException ex)
{
ex.printStackTrace();
System.out.println("made it here");
}
}

}
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know why this lasted so long in this forum. I am moving it to Sockets and Internet Protocols.
 
Chris Simpkins
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another option is the Apache Jakarta HttpClient. This page shows you how to instantiate a new httpclient, create the GET method, execute the method, and catch the exceptions that are thrown:

HttpClient Tutorial

Hope that this helps.

-Chris
 
Tamer Badr
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package NetworkUtils;

/**
* Utility for HTTP requests, it gives the ability to encode URLs , and request
* parameters by substituting any empty space in the URL with plus sign '+'.
*
* @author Tamer
* @version 1.0.0
*/
public abstract class QueryString {

/**
* Encodes an input <CODE>String</CODE>, in this version only empty spaces
* are substituted with the plus sign '+'.
*
* @param word The <CODE>String</CODE> to be encoded.
* @return The encoded <CODE>String</CODE>.
*/
public synchronized String encode(String word) {
String encoded = "";
encoded = word.replace(' ', '+');
return encoded;
}

/**
* Encodes the given name and value and returns them in a form of
* "name=value".
*
* @param name The parameter name.
* @param value The parameter value.
* @return The parameter encoded and in the form (name=value).
*/
public synchronized String encode(String name, String value) {
String encoded = "";
encoded += encode(name) + "=" + encode(value);
return encoded;
}

/**
* handles setting the request parameters.
*
* @param name The parameter name.
* @param value The parameter value.
*/
public abstract void addParam(String name, String value);

/**
* Holds value of property query.
*/
private String query = "";

/**
* Getter for property query.
*
* @return Value of property query.
*/
public String getQuery () {

return this.query;
}

/**
* Setter for property query.
* @param query New value of property query.
*/
public void setQuery (String query) {

this.query = query;
}
}





package NetworkUtils;

import java.net.*;
import java.io.*;

/**
* Utility for HTTP GET request, it gives the ability to form the request in an
* encoded form by adding the request parameters, and substituting any empty
* space in the URL with plus sign '+'.
*
* @author Tamer Badr
* @version 1.0.0
*/
public class GETQueryString extends QueryString {

/**
* Creates a new instance of GETQueryString
*
* @param url The basic URL for the form without any parameters.
*/
public GETQueryString(String url) {
if (url != null && !url.equals("") &&
url.toLowerCase ().startsWith ("http")) {
setQuery(encode(url));
} else {
throw new RuntimeException("URL to append to " + "\"" + url +
"\" is not a vlaid URL");
}
}

/**
* handles adding parameters to the end of the URL.
*
* @param name The parameter name.
* @param value The parameter value.
*/
public synchronized void addParam(String name, String value) {
String append = encode(name , value);
if (getQuery().indexOf('?') == -1) {
setQuery(getQuery() + "?" + append);
} else {
setQuery(getQuery() + "&" + append);
}
}
}





package NetworkUtils;

import java.net.*;
import java.io.*;

/**
* A <CODE>class</CODE> that handles sending HTTP GET requests and receiving
* responses.
*
* @author Tamer Badr
* @version 1.0.0
*/
public class HTTPGETImpl extends HTTPMethod {

/**
* Creates a new instance of <CODE>HTTPGETImpl</CODE>
*
* @param url A <CODE>QueryString</CODE> to connect to using GET method.
*/
public HTTPGETImpl(GETQueryString url) {
this.url = url;
}

/**
* Holds value of property url.
*/
private GETQueryString url;

/**
* Getter for property url.
*
* @return Value of property url.
*/
public GETQueryString getUrl() {

return this.url;
}

/**
* Setter for property url.
*
* @param url New value of property url.
*/
public void setUrl(GETQueryString url) {

this.url = url;
}

/**
* Sends the <CODE>HTTP</CODE> request, recieves the <CODE>HTTP</CODE> response,
* and stores it in the <CODE>String responseBody</CODE>.
*/
public synchronized void requestAndGetResponse() {
setResponseBody("");
try {
URL u = new URL(url.getQuery());
URLConnection uc = u.openConnection ();
BufferedReader in = new BufferedReader (new InputStreamReader(uc.getInputStream ( )));
String str;
while ((str = in.readLine ()) != null) {
setResponseBody(getResponseBody () + "\n" + str);
}
} catch (MalformedURLException murle) {
System.out.println(murle.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}

}
 
Tamer Badr
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, I forgot to send the HTTPMethod class code:



package NetworkUtils;

/**
* <CODE>HTTPMethod</CODE> is the <CODE>super class</CODE> for all classes that
* handle forming HTTP requests and responses.
*
* @author Tamer Badr
* @version 1.0.0
*/
public abstract class HTTPMethod {

/**
* Holds value of property responseBody.
*/
private String responseBody;

/**
* Getter for property responseBody.
* @return Value of property responseBody.
*/
public String getResponseBody () {

return this.responseBody;
}

/**
* Setter for property responseBody.
*
* @param responseBody New value of property responseBody.
*/
public void setResponseBody (String responseBody) {

this.responseBody = responseBody;
}

/**
* Sends the <CODE>HTTP</CODE> request, recieves the <CODE>HTTP</CODE> response,
* and stores it in the <CODE>String responseBody</CODE>.
*/
public abstract void requestAndGetResponse();

}
 
Damo Lameo
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi gerry

i just used your 'public class OAM' as you posted but modified the authorize

with this... code below... and it works for me

modify your line to read...

conn.setRequestProperty ("Authorization", "Basic "+base64Encode(username+":"+password));


public static final char [ ] alphabet = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0 to 7
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 8 to 15
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 16 to 23
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 24 to 31
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 32 to 39
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 40 to 47
'w', 'x', 'y', 'z', '0', '1', '2', '3', // 48 to 55
'4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

public static String base64Encode ( String s )
//////////////////////////////////////////////////////////////////////
{
return base64Encode ( s.getBytes ( ) );
}

public static String base64Encode ( byte [ ] octetString )
//////////////////////////////////////////////////////////////////////
{
int bits24;
int bits6;

char [ ] out
= new char [ ( ( octetString.length - 1 ) / 3 + 1 ) * 4 ];

int outIndex = 0;
int i = 0;

while ( ( i + 3 ) <= octetString.length )
{
// store the octets
bits24 = ( octetString [ i++ ] & 0xFF ) << 16;
bits24 |= ( octetString [ i++ ] & 0xFF ) << 8;
bits24 |= ( octetString [ i++ ] & 0xFF ) << 0;

bits6 = ( bits24 & 0x00FC0000 ) >> 18;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0003F000 ) >> 12;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x00000FC0 ) >> 6;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0000003F );
out [ outIndex++ ] = alphabet [ bits6 ];
}

if ( octetString.length - i == 2 )
{
// store the octets
bits24 = ( octetString [ i ] & 0xFF ) << 16;
bits24 |= ( octetString [ i + 1 ] & 0xFF ) << 8;

bits6 = ( bits24 & 0x00FC0000 ) >> 18;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0003F000 ) >> 12;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x00000FC0 ) >> 6;
out [ outIndex++ ] = alphabet [ bits6 ];

// padding
out [ outIndex++ ] = '=';
}
else if ( octetString.length - i == 1 )
{
// store the octets
bits24 = ( octetString [ i ] & 0xFF ) << 16;

bits6 = ( bits24 & 0x00FC0000 ) >> 18;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0003F000 ) >> 12;
out [ outIndex++ ] = alphabet [ bits6 ];

// padding
out [ outIndex++ ] = '=';
out [ outIndex++ ] = '=';
}

return new String ( out );
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic