List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.seeyon.apps.m1.common.manager.menu.impl.MMenuManagerImpl.java
/** * ?HttpURLConnection?//from w ww.j a va 2s . c o m * * @param in * @param urlPath * @param cookies * @return * @throws Exception */ private int getNum(String urlPath) { if (urlPath == null || urlPath.length() < 10) { return 0; } HttpURLConnection httpURLConnection = null; String resulet = ""; try { URL url = new URL(urlPath);// ??? httpURLConnection = (HttpURLConnection) url.openConnection(); // ? httpURLConnection.setDoOutput(true);// httpURLConnection.setRequestMethod("get");// ?? httpURLConnection.setUseCaches(false); httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); httpURLConnection.setDoInput(true);// ? httpURLConnection.setConnectTimeout(40000); // httpURLConnection.setReadTimeout(40000);// ? httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == 200) { InputStream in = httpURLConnection.getInputStream(); byte[] b = new byte[1024]; int lent = 0; while ((lent = in.read(b)) != -1) { resulet = resulet + new String(b, 0, lent); } in.close(); } return Integer.valueOf(resulet); } catch (Exception e) { e.printStackTrace(); } finally { httpURLConnection.disconnect(); } return 0; }
From source file:cz.incad.kramerius.k5indexer.Commiter.java
/** * Reads data from the data reader and posts it to solr, writes the response * to output/*from ww w. j a v a2 s.co m*/ */ private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(config.getInt("http.timeout", 10000)); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", contentType); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); int status = urlc.getResponseCode(); StringBuilder errorStream = new StringBuilder(); try { if (status != HttpURLConnection.HTTP_OK) { errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=") .append(status).append(" "); throw new Exception("URL=" + solrUrl + " HTTP response code=" + status); } Reader reader = new InputStreamReader(in); pipeString(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } InputStream es = urlc.getErrorStream(); if (es != null) { try { Reader reader = new InputStreamReader(es); pipeString(reader, errorStream); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (es != null) { es.close(); } } } if (errorStream.length() > 0) { throw new Exception("postData error: " + errorStream.toString()); } } catch (IOException e) { throw new Exception("Solr has throw an error. Check tomcat log. " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }
From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java
public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml, String soapAction) throws IOException, SOAPException { URI serviceLocation;/*from www . j av a 2s . c o m*/ try { serviceLocation = new URI(location); } catch (URISyntaxException e) { throw new IOException("Invalid uri for artifact resolve: " + location); } if (log.isDebugEnabled()) log.debug("serviceLocation..:" + serviceLocation); if (log.isDebugEnabled()) log.debug("SOAP Request: " + xml); HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection(); if (c instanceof HttpsURLConnection) { HttpsURLConnection sc = (HttpsURLConnection) c; if (ignoreCertPath) { sc.setSSLSocketFactory(new DummySSLSocketFactory()); sc.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } } c.setAllowUserInteraction(false); c.setDoInput(true); c.setDoOutput(true); c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length); c.setRequestMethod("POST"); c.setReadTimeout(20000); c.setConnectTimeout(30000); addContentTypeHeader(xml, c); c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\""); if (username != null && password != null) { c.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES)); } OutputStream outputStream = c.getOutputStream(); IOUtils.write(xml, outputStream, "UTF-8"); outputStream.flush(); outputStream.close(); if (c.getResponseCode() == 200) { InputStream inputStream = c.getInputStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP response: " + result); XMLObject res = SAMLUtil.unmarshallElementFromString(result); Envelope envelope = (Envelope) res; if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) { log.warn( "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server"); throw new SOAPException(c.getResponseCode(), result); } return envelope; } else { log.debug("Response code: " + c.getResponseCode()); InputStream inputStream = c.getErrorStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP fault: " + result); throw new SOAPException(c.getResponseCode(), result); } }
From source file:net.kourlas.voipms_sms.Api.java
private JSONObject getJson(String urlString) { try {//from w w w . j a v a 2 s .com URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder data = new StringBuilder(); String newLine = System.getProperty("line.separator"); String line; while ((line = reader.readLine()) != null) { data.append(line); data.append(newLine); } reader.close(); return new JSONObject(data.toString()); } catch (MalformedURLException ex) { return null; } catch (IOException ex) { return null; } catch (JSONException ex) { return null; } }
From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address address) { backgroundHandler.post(new Runnable() { @Override//from w w w . j a v a 2s . c o m public void run() { // Use either dogechain or chain.so List<String> urls = new ArrayList<String>(2); urls.add(Constants.DOGECHAIN_API_URL); urls.add(Constants.CHAINSO_API_URL); Collections.shuffle(urls, new Random(System.nanoTime())); final StringBuilder url = new StringBuilder(urls.get(0)); url.append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int success = json.getInt("success"); if (success != 1) throw new IOException("api status " + success + " when fetching unspent outputs"); final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash")); final int uxtoIndex = jsonOutput.getInt("tx_output_n"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
From source file:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java
/** * ?urlhttp/* www. ja v a 2s. co m*/ * * @param url * :url? * @return urlhttp * */ private HttpURLConnection getHttpConnection(String url) throws IOException, MalformedURLException, ProtocolException { HttpURLConnection httpConnection; httpConnection = ((HttpURLConnection) new URL(url).openConnection()); httpConnection.setConnectTimeout(mTimeout); httpConnection.setRequestMethod("POST"); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); return httpConnection; }
From source file:count.ly.messaging.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { String urlStr = serverURL_ + "/i?"; if (!eventData.contains("&crash=")) urlStr += eventData;//from w ww . j av a2 s . c o m final URL url = new URL(urlStr); final HttpURLConnection conn; if (Countly.publicKeyPinCertificates == null) { conn = (HttpURLConnection) url.openConnection(); } else { HttpsURLConnection c = (HttpsURLConnection) url.openConnection(); c.setSSLSocketFactory(sslContext_.getSocketFactory()); conn = c; } conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false); conn.setDoInput(true); String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else if (eventData.contains("&crash=")) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Using post because of crash"); } conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(eventData); writer.flush(); writer.close(); os.close(); } else { conn.setDoOutput(false); } return conn; }
From source file:com.norconex.committer.idol.IdolCommitter.java
/** * Creates a HTTP URL connection with the proper Post method and properties. * @param url the URL to open//w w w . jav a 2 s .co m * @return HttpUrlConnection object */ private HttpURLConnection createURLConnection(String url) { URL targetURL; HttpURLConnection con = null; try { targetURL = new URL(url); con = (HttpURLConnection) targetURL.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // add request header con.setRequestMethod("POST"); } catch (MalformedURLException e) { LOG.error("Something went wrong with the URL: " + url, e); } catch (IOException e) { LOG.error("I got an I/O problem trying to connect to the server", e); } return con; }
From source file:ja.ohac.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override/*from www . j a va 2 s . c o m*/ public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = BaseEncoding.base16().lowerCase() .decode(jsonOutput.getString("script_pub_key")); final BigInteger uxtoValue = new BigInteger(jsonOutput.getString("value")); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.valueOf(uxtoValue.longValue()), uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override//from w w w .j av a 2 s .co m public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }