Today is a good day to code

Doing an Http Request in Java

Posted: December 31st, 1969 | Author: | Filed under: Companies, java, Programming, Sun Microsystems | Tags: , , | 1 Comment »

Doing an Http Request in Java

Picture of IrvinSince I always forget how to do this, because I just reuse a class, I am selfishly going to post the code for an HTTP request in Java to this blog. I don’t think I am using anything specific to JDK 1.5, but I very well could be.
/*
* MakeHttpRequest.java
*
* Created on May 15, 2007, 8:40 PM by Irvin Owens Jr
*/ 

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MakeHttpRequest {

private String myUri;

/** Creates a new instance of MakeHttpRequest */
public MakeHttpRequest(String uri) {
this.myUri = uri;
}

public String doRequest(){
String req = null;
try {
req = makeHttpRequest();
} catch (IOException ex) {
ex.printStackTrace();
}
return req;
}

private String makeHttpRequest() throws IOException{
String str = null;
URL hp = new URL(this.myUri);
URLConnection conn = hp.openConnection();

Here I am going to set a User Agent string by getting some information from my Java Environment, along with additional information.
conn.addRequestProperty("User-Agent","WelshCorgi/1.0(WC 1.0; " + System.getProperty("os.version") + "; " + System.getProperty("os.version") + "; " + System.getProperty("os.arch") + ") Corgi/1.0.0.0");
InputStream input = conn.getInputStream();
conn.connect();
String mime = conn.getContentType();

I have a thread spin off to write the file to a cache.

Main.corgiExecutor.execute(new SaveBinaryFile(input,"wc/cache/wc_cache_" + this.myUri.replaceAll("\p{Punct}","_") + "." + getFileExtension(mime)));
//new SaveBinaryFile(input,"cache/" + this.myUri.replaceAll(":punct:","_")).run();

Then I check the mime type to make sure that it is markup. It would probably be prudent to check for the xml type also.
if(mime.equals("html") || mime.equals("text")){
// Get response data.
BufferedReader inputData = new BufferedReader(new InputStreamReader(input));
StringBuilder sb = new StringBuilder();
while (null != ((str = inputData.readLine()))){
sb.append(str);
}
str = str.toString();
}
return str;

private String getFileExtension(String mime){
String ext = null;
if(mime.contains("html")){
ext = "html";
}else if(mime.contains("text")){
ext = "text";
}else if(mime.contains("gif")){
ext = "gif";
}else if(mime.contains("jpeg")){
ext = "jpg";
}else if(mime.contains("swf")){
ext = "swf";
}
return ext;
}

}
That should be enough to get you started with the http request. Its pretty simple once you get used to it.


  • dmkim

    Thank you very much..
    I have a big problem (http 403 error).
    but, you code is the solution…

    Thank you so much :-)