Reading HTTP server response using java


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

public class ReadServerResponse {

private static final String USER_AGENT = "Mozilla/5.0";
private String URL;

public ReadServerResponse(String url){
this.URL = url;
}

public static void main(String[] args) {
ReadServerResponse readServerResponse =
new ReadServerResponse("<Your UR>");
StringBuffer response = readServerResponse.getServerResponse();
System.out.println(response);
}

public StringBuffer getServerResponse() {
StringBuffer buffer = new StringBuffer();
try {
URL unifromResourceIdentifier = new URL(this.URL);
HttpURLConnection httpConnection = (HttpURLConnection) unifromResourceIdentifier.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("User-Agent", USER_AGENT);
int statusCode = httpConnection.getResponseCode();
if(statusCode == HttpURLConnection.HTTP_OK) {
InputStream is = httpConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));

String inputLine;

while ((inputLine = in.readLine()) != null) {
               buffer.append(inputLine);
           }
           in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return buffer;
}
}

No comments:

Post a Comment