[Java] How to Create a HTTP Get Request

Basically i use this class to mimic a json request to a different domain, to prevent CORS error. So this is my code, oh and i use Spring Framework, which explain the Service annotation .

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.springframework.stereotype.Service;

public class JsonService {

    public String get() {
        try {
            return getHTML("myurl");
        } catch (Exception e) {
            return "";
   private String getHTML(String urlToRead) throws Exception {
      StringBuilder result = new StringBuilder();
      URL url = new URL(urlToRead);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      return result.toString();

Hope it can help others, cheers (B)

No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked