List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.example.appengine.appidentity.UrlShortener.java
/** * Returns a shortened URL by calling the Google URL Shortener API. * * <p>Note: Error handling elided for simplicity. *//*from w ww . ja va2 s.c om*/ public String createShortUrl(String longUrl) throws Exception { ArrayList<String> scopes = new ArrayList<String>(); scopes.add("https://www.googleapis.com/auth/urlshortener"); final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); // The token asserts the identity reported by appIdentity.getServiceAccountName() JSONObject request = new JSONObject(); request.put("longUrl", longUrl); URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken()); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); request.write(writer); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Note: Should check the content-encoding. // Any JSON parser can be used; this one is used for illustrative purposes. JSONTokener responseTokens = new JSONTokener(connection.getInputStream()); JSONObject response = new JSONObject(responseTokens); return (String) response.get("id"); } else { try (InputStream s = connection.getErrorStream(); InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) { throw new RuntimeException(String.format("got error (%d) response %s from %s", connection.getResponseCode(), CharStreams.toString(r), connection.toString())); } } }
From source file:com.orchestra.portale.external.services.manager.BikeSharingService.java
@Override public String getResponse(Map<String, String[]> mapParams) { try {// w w w .j a v a 2 s. c om HttpURLConnection urlConnection = (HttpURLConnection) new URL(baseUrl).openConnection(); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(30000); urlConnection.addRequestProperty("Accept-Language", Locale.getDefault().toString().replace('_', '-')); String result = IOUtils.toString(urlConnection.getInputStream()); urlConnection.disconnect(); return result; } catch (IOException e) { return "response{code:1,error:" + e.getMessage() + "}"; } }
From source file:com.google.gwt.benchmark.compileserver.server.manager.BenchmarkReporter.java
private boolean postResultToServer(String json) { OutputStream out = null;//w w w .j ava 2 s . c o m try { HttpURLConnection httpCon = httpURLConnectionFactory.create(); httpCon.addRequestProperty("auth", reporterSecret); httpCon.setDoOutput(true); httpCon.setRequestMethod("PUT"); out = httpCon.getOutputStream(); out.write(json.getBytes("UTF-8")); if (httpCon.getResponseCode() == HTTP_OK) { return true; } } catch (IOException e) { logger.log(Level.WARNING, "Could not post results to server", e); } finally { IOUtils.closeQuietly(out); } return false; }
From source file:ru.dmitry.mamishev.URLParse.HtmlString.java
private HtmlString getStringFromURL(String sUrl, String charSet) { String sHTML = "Can not load page"; URL url;/*from w w w .ja va 2 s. co m*/ InputStream is; BufferedReader buff = null; //URLConnection con; HttpURLConnection con; try { url = new URL(sUrl); con = (HttpURLConnection) url.openConnection(); con.addRequestProperty("Cookie", "PHPSESSID=ecc618552b072f22c3494b8fefae2142"); is = con.getInputStream(); //is = url.openConnection().getInputStream(); buff = new BufferedReader(new InputStreamReader(is, charSet)); StringBuilder page = new StringBuilder(); String tmp; while ((tmp = buff.readLine()) != null) { page.append(tmp).append("\n"); //System.out.println(tmp); } System.out.println(); sHTML = page.toString(); } catch (MalformedURLException ex) { Logger.getLogger(URLTest.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(URLTest.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (buff != null) { buff.close(); } } catch (IOException ex) { Logger.getLogger(URLTest.class.getName()).log(Level.SEVERE, null, ex); } } return new HtmlString(sHTML); }
From source file:com.psbk.modulperwalian.Controller.DosenMain.java
public List<Perwalian> getMhsHasPerwalian() throws Exception { waliList = new ArrayList<>(); String url = "dosen/getMhsWali/dos01"; obj = new URL(BASE_URL + url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine;//w ww . ja v a 2s. c om StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject result; JSONObject jsonObject = new JSONObject(response.toString()); JSONArray jsonArray = (JSONArray) jsonObject.get("result"); // // if (jsonArray.isNull(0)) { // waliList = null; // // } // else { System.out.println(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject objek = (JSONObject) jsonArray.get(i); result = (JSONObject) objek.get("map"); String status = result.getString("status"); // if (status.matches("sudah")) { Perwalian ps = new Perwalian(); ps.getMhs().setNama(result.getString("nama")); System.out.println(ps.getMhs().getNama()); ps.getMhs().setNrp(result.getString("nrp")); waliList.add(ps); } } // } return waliList; }
From source file:org.openhab.io.multimedia.internal.tts.TTSServiceGoogleTTS.java
/** * Connects to the given {@link URL} and returns the response as an {@link InputStream}. * // w w w . j av a2 s. c o m * @param url * The {@link URL} to connect to * @return The response as {@link InputStream} * @throws IOException * Exception if the connection could not be established properly */ private InputStream getInputStreamFromUrl(URL url) throws IOException { logger.debug("Connecting to URL " + url.toString()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("User-Agent", USER_AGENT); connection.connect(); return new BufferedInputStream(connection.getInputStream()); }
From source file:au.id.tmm.anewreader.model.net.ReaderServiceAuthenticationHelper.java
/** * {@inheritDoc}// ww w . ja va 2 s. co m */ @Override public HttpURLConnection addAuthenticationHeaders(HttpURLConnection connection) { if (this.hasToken()) { connection.addRequestProperty(AUTHORISATION_FIELD_TITLE, AUTHORISATION_FIELD_PREFIX + this.authToken); return connection; } else { throw new IllegalStateException( "Attempted to add authentication headers with out " + "retrieving token"); } }
From source file:com.psbk.modulperwalian.Controller.StudentController.java
public List<Mahasiswa> getListStudents() throws Exception { listStudents = new ArrayList<>(); String url = "mhsByNrp/02"; URL obj = new URL(BASE_URL + url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine;/*from ww w .j a v a 2 s .c om*/ StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject result; JSONObject jsonObject = new JSONObject(response.toString()); result = (JSONObject) jsonObject.get("result"); result = (JSONObject) result.get("map"); Mahasiswa s = new Mahasiswa(); s.setNrp(result.get("nrp").toString()); s.setNama(result.getString("nama")); s.setAlamat(result.getString("alamat")); listStudents.add(s); return listStudents; }
From source file:com.psbk.modulperwalian.Controller.StudentController.java
public Mahasiswa getDataMhs() throws Exception { String url = "mhsByNrp/02"; URL obj = new URL(BASE_URL + url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine;/*from w w w .j a va 2s. co m*/ StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject result; JSONObject jsonObject = new JSONObject(response.toString()); result = (JSONObject) jsonObject.get("result"); result = (JSONObject) result.get("map"); Mahasiswa s = new Mahasiswa(); s.setNrp(result.get("nrp").toString()); s.setNama(result.getString("nama")); s.setAlamat(result.getString("alamat")); s.setTgl(result.getString("tglLahir")); s.setNoTelp(result.getString("noTelp")); s.setEmail(result.getString("email")); s.setIpk(result.getDouble("ipk")); return s; }
From source file:org.wisdom.openid.connect.service.internal.DefaultIssuer.java
@Override public TokenResponse authorizationToken(final String redirectUrl, final String code) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("grant_type=authorization_code"); sb.append(format("&code=%s", code)); sb.append(format("&client_id=%s", clientId)); sb.append(format("&client_secret=%s", clientSecret)); sb.append(format("&redirect_uri=%s", redirectUrl)); String parameters = sb.toString(); URL tokenEndpoint = new URL(config.getTokenEndpoint()); HttpURLConnection connection = (HttpURLConnection) tokenEndpoint.openConnection(); connection.setRequestMethod("POST"); connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //connection.addRequestProperty("Authorization", format("Basic %s", credentials())); connection.setRequestProperty("Content-Length", valueOf(parameters.getBytes().length)); connection.setUseCaches(false);//from w w w .j av a2 s . c o m connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); //Get Response return buildTokenResponse(connection.getInputStream()); }