How to connect to a website with Java

//How to connect to a website with Java

How to make a GET or POST Request with Java ?

If you want to get or send some data to a website here is a code example how to do it.
In this example it’s a GET Request, that can also be used to set some cookies, user agent , and more.

At the end of the code you can found a JSON Decode example.

The data is decoded using Gzip because of the “Accept-Encoding” tag set to Gzip.

url = new URL("https://google.com");			
HttpURLConnection conn = (HttpURLConnection) url.openConnection();	
conn.setReadTimeout(5000);			
conn.setRequestProperty("Cookie"," ");
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("charset", "utf-8");
conn.addRequestProperty("Cache-Control", "max-age=0");
conn.addRequestProperty("Accept-Encoding", "gzip");
conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36");
conn.addRequestProperty("Referer", "google.com");
conn.setUseCaches( false );
conn.setRequestMethod("GET");
conn.disconnect();

Reader reader = null;
if ("gzip".equals(conn.getContentEncoding())) {
reader = new InputStreamReader(new GZIPInputStream(conn.getInputStream()));
}else{
reader = new InputStreamReader(conn.getInputStream());
}

StringBuilder sb = new StringBuilder();
while (true) {
int ch = reader.read();
if (ch==-1) {
break;
}
sb.append((char)ch);
System.out.print((char)ch);
}

conn.getInputStream().close();	

/* Get Json data from a page
JSONParser parser = new JSONParser();
Object obj = parser.parse(sb.toString());
JSONObject jsonObject = (JSONObject) obj;

String online = (String) jsonObject.get("online");
*/
By | 2017-02-11T12:49:04+00:00 February 10th, 2017|0 Comments

Leave A Comment