[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; @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(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } }
Hope it can help others, cheers
No Comments