List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:net.peterkuterna.appengine.apps.devoxxsched.util.Md5Calculator.java
private byte[] getResponse(final String requestUri) { try {/*w ww. j ava 2s.c o m*/ URL url = new URL(requestUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-agent", "Devoxx Schedule AppEngine Backend"); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(120 * 1000); connection.setRequestProperty("Cache-Control", "no-cache,max-age=0"); connection.setRequestProperty("Pragma", "no-cache"); InputStream response = connection.getInputStream(); log.info("response = " + connection.getResponseCode()); if (connection.getResponseCode() == 200) { return IOUtils.toByteArray(response); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.giga.warehouse.RestExampleIT.java
@Test public void shouldAccessInitialPage() throws Exception { URL url = new URL("http://localhost:8181/modeshape-rest-example/restful-services/warehouse"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); //connection.set assertEquals(200, connection.getResponseCode()); System.out.println(IOUtils.toString(connection.getInputStream())); System.out.println(connection.getContentType()); }
From source file:com.adguard.commons.web.UrlUtils.java
/** * Downloads content from the specified url using specified proxy (or do not using it) and timeouts. * Returns null if there's an error./*from ww w . j ava 2s . c o m*/ * * @param url url * @param proxy proxy to use * @param readTimeout read timeout * @param socketTimeout connection timeout * @return Downloaded string */ public static String downloadString(URL url, Proxy proxy, int readTimeout, int socketTimeout, String encoding) { HttpURLConnection connection = null; InputStream inputStream = null; try { connection = (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy)); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36"); connection.setReadTimeout(readTimeout); connection.setConnectTimeout(socketTimeout); connection.connect(); if (connection.getResponseCode() >= 400) { throw new IOException("Response status is " + connection.getResponseCode()); } if (connection.getResponseCode() >= 301) { String location = connection.getHeaderField("Location"); // HttpURLConnection does not follow redirects from HTTP to HTTPS // So we handle it manually return downloadString(new URL(location), proxy, readTimeout, socketTimeout, encoding); } if (connection.getResponseCode() == 204) { return StringUtils.EMPTY; } inputStream = connection.getInputStream(); return IOUtils.toString(inputStream, encoding); } catch (IOException ex) { if (LOG.isDebugEnabled()) { LOG.warn("Error downloading string from {}:\r\n", url, ex); } else { LOG.warn("Cannot download string from {}: {}", url, ex.getMessage()); } // Ignoring exception return null; } finally { IOUtils.closeQuietly(inputStream); if (connection != null) { connection.disconnect(); } } }
From source file:com.xiaoerge.littleastroapi.reading.ZodiacReadings.java
private ZodiacReadings() throws ConfigurationException, IOException { PropertiesConfiguration configs = new PropertiesConfiguration("app.properties"); String horoscopeRest = configs.getString("app.zodiac.rest.get"); HttpURLConnection con = (HttpURLConnection) new URL(horoscopeRest).openConnection(); con.setRequestProperty("User-Agent", "LittleAstro-API-Java"); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String jstring = reader.readLine(); Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(jstring).getAsJsonArray(); signs = new ArrayList<ZodiacSign>(); for (JsonElement obj : jArray) { ZodiacSign sign = gson.fromJson(obj, ZodiacSign.class); signs.add(sign);// w w w . j a v a 2 s . com } }
From source file:acclaim.Acclaim.java
public String doHTTPGetRequest(String url) throws Exception { URL obj = new URL(BASE_URL + url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization", authString); con.setRequestProperty("Content-Type", "application/json"); int responseCode = con.getResponseCode(); //System.out.println("\nSending 'GET' request to URL : " + url); //System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine;//from w w w . j a va 2s . c om StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); }
From source file:com.qpark.eip.core.spring.security.https.EipHttpsUrlConnectionMessageSender.java
/** * @see org.springframework.ws.transport.http.HttpsUrlConnectionMessageSender#prepareConnection(java.net.HttpURLConnection) *///from w ww. j ava2s . c om @Override protected void prepareConnection(final HttpURLConnection connection) throws IOException { if (HttpsURLConnection.class.isInstance(connection)) { this.setHostnameVerifier(this.x509TrustManager); this.setTrustManagers(new TrustManager[] { this.x509TrustManager }); } /* call the super method. */ super.prepareConnection(connection); /* Setup the basic Authentication. */ if (HttpURLConnection.class.isInstance(connection) && this.userName != null) { HttpURLConnection httpsConnection = connection; httpsConnection.setRequestProperty("Authorization", new StringBuffer(128).append("Basic ").append(this.base64UserNamePassword).toString()); } }
From source file:javaapplication1.Prog.java
public void transferStuff(String obj, String user) throws MalformedURLException, IOException { URL object = new URL("http://localhost:8080/bankserver/users/" + user); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true);//from w ww. ja v a2 s. com con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestMethod("PUT"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(obj); wr.flush(); wr.close(); con.getInputStream(); }
From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.collection.JsonObjectRequest.java
/** * Helper method to make an HTTP request. * @param urlConnection The HTTP connection. *//*from w w w.ja va 2s.c om*/ public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestMethod("POST"); OutputStream os = urlConnection.getOutputStream(); os.write(mJsonObject.toString().getBytes("UTF-8")); os.close(); }
From source file:net.ae97.pokebot.extensions.scrolls.StatCommand.java
@Override public void runEvent(CommandEvent event) { try {//from ww w .j a v a 2 s . c om List<String> lines = new LinkedList<>(); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION); conn.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(StringUtils.join(lines, "\n")); JsonObject obj = element.getAsJsonObject(); JsonObject dataObject = obj.get("data").getAsJsonObject(); StringBuilder builder = new StringBuilder(); builder.append("Stats - "); builder.append("Online today: ").append(dataObject.get("onlinetoday").getAsInt()); builder.append(" - "); builder.append("Gold earned: ").append(dataObject.get("goldearned").getAsInt()); builder.append(" - "); builder.append("Games played: ").append(dataObject.get("gamesplayed").getAsInt()); builder.append(" - "); builder.append("Total users: ").append(dataObject.get("totalusers").getAsInt()); String message = builder.toString(); event.respond(message); } catch (IOException | JsonSyntaxException ex) { PokeBot.getLogger().log(Level.SEVERE, "Error on getting stats for Scrolls", ex); event.respond("Error on getting stats: " + ex.getLocalizedMessage()); } }
From source file:com.google.cloud.trace.zipkin.autoconfigure.ZipkinStackdriverStorageAutoConfiguration.java
String getDefaultProjectId() throws IOException { URL url = new URL("http://metadata.google.internal/computeMetadata/v1/project/project-id"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Metadata-Flavor", "Google"); connection.setRequestMethod("GET"); try (InputStream responseStream = connection.getInputStream()) { String projectId = new String(ByteStreams.toByteArray(responseStream)); return projectId; }//from w w w . jav a 2s . c o m }