List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.joyent.manta.client.MantaClientSigningIT.java
@Test public final void testCanCreateSignedURIWithEncodedCharacters() throws IOException { final String path = testPathPrefix + " quack "; mantaClient.put(path, TEST_DATA, UTF_8); Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA); final URI uri = mantaClient.getAsSignedURI(path, "GET", Instant.now().plus(Duration.ofHours(1))); final HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); try (final InputStream is = conn.getInputStream()) { conn.setReadTimeout(3000);// w ww. ja v a2s .c o m conn.connect(); Assert.assertEquals(conn.getResponseCode(), HttpStatus.SC_OK); Assert.assertEquals(IOUtils.toString(is, UTF_8), TEST_DATA); } finally { conn.disconnect(); } }
From source file:it.telecomitalia.my.base_struct_apps.VersionUpdate.java
@Override protected Void doInBackground(String... urls) { /* metodo principale per aggiornamento */ String xml = ""; try {/*from w w w .ja v a 2s. com*/ /* tento di leggermi il file XML remoto */ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); /* ora in xml c' il codice della pagina degli aggiornamenti */ } catch (IOException e) { e.printStackTrace(); } // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile try { /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti. * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione la * applicazione sul server.*/ DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); Document dom = db.parse(is); Element element = dom.getDocumentElement(); Element current = (Element) element.getElementsByTagName("current").item(0); currentVersion = current.getAttribute("value"); currentApkName = current.getAttribute("apk"); } catch (Exception e) { e.printStackTrace(); } /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */ if (currentVersion != null & runningVersion != null) { /* esistono, li trasformo in double */ Double serverVersion = Double.parseDouble(currentVersion); Double localVersion = Double.parseDouble(runningVersion); /* La versione server superiore alla mia ! Occorre aggiornare */ if (serverVersion > localVersion) { try { /* connessione al server */ URL urlAPK = new URL(SERVER + PATH + currentApkName); HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection(); con.setRequestMethod("GET"); con.setDoOutput(true); con.connect(); // qual' la tua directory di sistema Download ? File downloadPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File outputFile = new File(downloadPath, currentApkName); //Log.i("test", downloadPath.getAbsolutePath()); //Log.i("test", outputFile.getAbsolutePath()); // se esistono download parziali o vecchi, li elimino. if (outputFile.exists()) outputFile.delete(); /* mi creo due File Stream uno di input, quello che sto scaricando dal server, * e l'altro di output, quello che sto creando nella directory Download*/ InputStream input = con.getInputStream(); FileOutputStream output = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int count = 0; while ((count = input.read(buffer)) != -1) { output.write(buffer, 0, count); } output.close(); input.close(); /* una volta terminato il processo, attraverso un intent lancio il file che ho * appena scaricato in modo da installare immediatamente l'aggiornamento come * specificato qui * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/ Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } } return null; }
From source file:id.nci.stm_9.HkpKeyServer.java
private String query(String request) throws QueryException, HttpError { InetAddress ips[];/*from ww w. java2 s . c o m*/ try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); }
From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java
@NotNull protected Tuple2<Integer, JsonNode> fetchJson(final String rel, final boolean post) throws Exception { final JsonFactory factory = new JsonFactory(); final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection(); try {//from w w w . ja v a 2 s. c o m conn.setRequestMethod(post ? "POST" : "GET"); conn.setRequestProperty("Accept", "application/json"); conn.connect(); final int responseCode = conn.getResponseCode(); InputStream in; try { in = conn.getInputStream(); } catch (final IOException e) { in = conn.getErrorStream(); } if (in == null) { return Tuple2.tuple2(responseCode, (JsonNode) MissingNode.getInstance()); } assertEquals("application/json", conn.getHeaderField("Content-Type")); try { final ObjectMapper om = new ObjectMapper(); return Tuple2.tuple2(responseCode, om.reader().with(factory).readTree(in)); } finally { in.close(); } } finally { conn.disconnect(); } }
From source file:com.baidu.jprotobuf.rpc.client.HttpRPCServerTest.java
protected void testIDLClientQuery(String inputIDL, String outputIDL) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL( "http://localhost:8080/SimpleIDLTest?" + ServiceExporter.INPUT_IDL_PARAMETER + "=aa") .openConnection();// w ww . j av a 2 s . c o m connection.connect(); byte[] readResponse = readResponse(connection); Assert.assertEquals(inputIDL, new String(readResponse)); connection = (HttpURLConnection) new URL( "http://localhost:8080/SimpleIDLTest?" + ServiceExporter.OUTPUT_IDL_PARAMETER + "=aa") .openConnection(); connection.connect(); readResponse = readResponse(connection); Assert.assertEquals(outputIDL, new String(readResponse)); }
From source file:org.ednovo.goorusearchwidget.WebService.java
public InputStream getHttpStream(String urlString) throws IOException { InputStream in = null;//from w w w . jav a 2 s . co m int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); Log.i("Response code :", "" + response); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception e) { throw new IOException("Error connecting"); } // end try-catch return in; }
From source file:com.jug6ernaut.android.utilites.FileDownloader.java
public File downloadFile(File serverFile, File outputFile) throws IOException { long total = 0; long progress = 0; status = 0;//from ww w . ja v a 2s . c om String stringURL = serverFile.getPath(); //fix url as File removes // if (stringURL.startsWith("http:/") && !stringURL.startsWith("http://")) stringURL = stringURL.replace("http:/", "http://"); if (stringURL.startsWith("https:/") && !stringURL.startsWith("https://")) stringURL = stringURL.replace("https:/", "https://"); try { URL url = new URL(stringURL); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); File dir = outputFile.getParentFile(); dir.mkdirs(); FileOutputStream fos = new FileOutputStream(outputFile); total = c.getContentLength(); startTalker(total); InputStream is = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1); progressTalker(len1); progress += len1; } finishTalker(progress); fos.close(); is.close(); } catch (Exception e) { cancelTalker(e); e.printStackTrace(); status = STATUS_FAILED; return null; } if (total == progress) status = STATUS_SUCCESS; else status = STATUS_FAILED; return outputFile; }
From source file:com.joyent.manta.client.MantaClientSigningIT.java
@Test public final void testCanCreateSignedGETUriFromPath() throws IOException { if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); }//from w w w . ja v a 2s . c om final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA); // This will throw an error if the newly inserted object isn't present mantaClient.head(path); Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "GET", expires); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); try (InputStream is = connection.getInputStream()) { connection.setReadTimeout(3000); connection.connect(); if (connection.getResponseCode() != 200) { Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset())); } String actual = IOUtils.toString(is, Charset.defaultCharset()); Assert.assertEquals(actual, TEST_DATA); } finally { connection.disconnect(); } }
From source file:com.huixueyun.tifenwang.api.net.HttpEngine.java
/** * http urlconnection?/*from w w w . j av a 2s .com*/ * * @param paramsMap ?? * @param model ? * @param paramUrl ?? * @param type ? * @param <T> * @return ApiResponse? * @throws IOException */ public <T> T postConnectionHandle(Map<String, String> paramsMap, String model, String paramUrl, String type) throws IOException { String data = joinParams(paramsMap, type); // ? L.e(data); HttpURLConnection connection = getConnection(paramUrl); connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length)); connection.connect(); OutputStream os = connection.getOutputStream(); os.write(data.getBytes()); os.flush(); if (connection.getResponseCode() == 200) { // ??? InputStream is = connection.getInputStream(); // ? ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ? int len = 0; // byte buffer[] = new byte[1024]; // ?? while ((len = is.read(buffer)) != -1) { // ??os baos.write(buffer, 0, len); } // ? is.close(); baos.close(); connection.disconnect(); // final String result = new String(baos.toByteArray()); ApiResponse apiResponse; try { apiResponse = ApiModel.getInstance().getApiResponse(model, result); } catch (Exception e) { apiResponse = null; } return (T) apiResponse; } else { connection.disconnect(); return null; } }
From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java
public static String sendHttpMessage(String endpoint, String message) throws Exception { if ((message == null) || (endpoint == null)) { throw new Exception("Message and Endpoint must both be set"); }//from ww w .j av a 2 s . co m String newPostBody = message; byte newPostBodyBytes[] = newPostBody.getBytes(); URL url = new URL(endpoint); logger.info(">> " + url.toString()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); // POST no matter what con.setDoOutput(true); con.setDoInput(true); con.setFollowRedirects(false); con.setUseCaches(true); logger.info(">> " + "GET"); //con.setRequestProperty("content-length", newPostBody.length() + ""); con.setRequestProperty("host", url.getHost()); con.connect(); logger.info(">> " + newPostBody); int statusCode = con.getResponseCode(); BufferedInputStream responseStream; logger.info("StatusCode:" + statusCode); if (statusCode != 200 && statusCode != 201) { responseStream = new BufferedInputStream(con.getErrorStream()); } else { responseStream = new BufferedInputStream(con.getInputStream()); } int b; String response = ""; while ((b = responseStream.read()) != -1) { response += (char) b; } logger.info("response:" + response); return response; }