List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.linkedin.pinot.tools.perf.PerfBenchmarkDriver.java
public JSONObject postQuery(String query, String optimizationFlags) throws Exception { JSONObject requestJson = new JSONObject(); requestJson.put("pql", query); if (optimizationFlags != null && !optimizationFlags.isEmpty()) { requestJson.put("debugOptions", "optimizationFlags=" + optimizationFlags); }/*from ww w .ja v a2s.c o m*/ long start = System.currentTimeMillis(); URLConnection conn = new URL(_brokerBaseApiUrl + "/query").openConnection(); conn.setDoOutput(true); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"))) { String requestString = requestJson.toString(); writer.write(requestString); writer.flush(); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"))) { String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } } long totalTime = System.currentTimeMillis() - start; String responseString = stringBuilder.toString(); JSONObject responseJson = new JSONObject(responseString); responseJson.put("totalTime", totalTime); if (_verbose && (responseJson.getLong("numDocsScanned") > 0)) { LOGGER.info("requestString: {}", requestString); LOGGER.info("responseString: {}", responseString); } return responseJson; } }
From source file:org.jab.docsearch.utils.NetUtils.java
/** * Get SpiderUrl status//from w w w .ja v a 2 s .c o m * * Content type, content length, last modified and md5 will be set in SpiderUrl if url is changed * * @param spiderUrl URL to check * @param file URL content downloads to to this file * @return -1 if link is broken, 0 if the file is unchanged or 1 if the file * is different... part of caching algoritm. */ public int getURLStatus(final SpiderUrl spiderUrl, final String file) { // -1 means broken link // 0 means same file // 1 means changed int status; try { // attempt to obtain status from date URL url = new URL(spiderUrl.getUrl()); URLConnection conn = url.openConnection(); // set connection parameter conn.setDoInput(true); conn.setDoOutput(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", USER_AGENT); // connect conn.connect(); // content type spiderUrl.setContentType(getContentType(conn)); // check date long spiDate = spiderUrl.getLastModified(); long urlDate = conn.getLastModified(); // same if date is equal and not zero if (spiDate == urlDate && urlDate != 0) { // the file is not changed status = 0; } else { // download the URL and compare hashes boolean downloaded = downloadURLToFile(conn, file); if (downloaded) { // download ok // compare file hashes String fileHash = FileUtils.getMD5Sum(file); if (fileHash.equals(spiderUrl.getMd5())) { // same status = 0; } else { // changed status = 1; // set changed values spiderUrl.setSize(FileUtils.getFileSize(file)); spiderUrl.setLastModified(urlDate); spiderUrl.setMd5(fileHash); } } else { // download failed // broken link status = -1; } } } catch (IOException ioe) { logger.error("getURLStatus() failed for URL='" + spiderUrl.getUrl() + "'", ioe); status = -1; } return status; }
From source file:screenieup.ImgurUpload.java
/** * Connect to image host./* ww w . j a va 2 s .c o m*/ * @return the connection */ private URLConnection connect() { URLConnection conn = null; try { System.out.println("Connecting to imgur..."); // opens connection and sends data URL url = new URL(IMGUR_POST_URI); conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Authorization", "Client-ID " + IMGUR_API_KEY); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } catch (MalformedURLException ex) { Logger.getLogger(ImgurUpload.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ImgurUpload.class.getName()).log(Level.SEVERE, null, ex); } return conn; }
From source file:africastalkinggateway.AfricasTalkingGateway.java
private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception { try {/*w w w .ja va 2 s . c om*/ String data = new String(); Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8"); data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8"); if (it.hasNext()) data += "&"; } URL url = new URL(urlString_); URLConnection conn = url.openConnection(); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("apikey", _apiKey); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); HttpURLConnection http_conn = (HttpURLConnection) conn; responseCode = http_conn.getResponseCode(); BufferedReader reader; if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED) reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream())); else reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream())); String response = reader.readLine(); if (DEBUG) System.out.println(response); reader.close(); return response; } catch (Exception e) { throw e; } }
From source file:org.apache.servicemix.jbi.itests.IntegrationTest.java
@Test public void testServiceAssembly() throws Throwable { System.out.println("Waiting for NMR"); NMR nmr = getOsgiService(NMR.class); assertNotNull(nmr);//from ww w .jav a2 s .c o m Bundle smxShared = installJbiBundle("org.apache.servicemix", "servicemix-shared", "installer", "zip"); Bundle smxJsr181 = installJbiBundle("org.apache.servicemix", "servicemix-jsr181", "installer", "zip"); Bundle smxHttp = installJbiBundle("org.apache.servicemix", "servicemix-http", "installer", "zip"); Bundle saBundle = installJbiBundle("org.apache.servicemix.samples.wsdl-first", "wsdl-first-sa", null, "zip"); smxShared.start(); smxJsr181.start(); smxHttp.start(); saBundle.start(); System.out.println("Waiting for JBI Service Assembly"); ServiceAssembly sa = getOsgiService(ServiceAssembly.class); assertNotNull(sa); Thread.sleep(500); final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>(); final int nbThreads = 2; final int nbMessagesPerThread = 10; final CountDownLatch latch = new CountDownLatch(nbThreads * nbMessagesPerThread); for (int i = 0; i < nbThreads; i++) { new Thread() { public void run() { for (int i = 0; i < nbMessagesPerThread; i++) { try { URL url = new URL("http://localhost:8192/PersonService/"); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.getOutputStream().write( ("<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + " xmlns:tns=\"http://servicemix.apache.org/samples/wsdl-first/types\">\n" + " <env:Body>\n" + " <tns:GetPerson>\n" + " <tns:personId>world</tns:personId>\n" + " </tns:GetPerson>\n" + " </env:Body>\n" + "</env:Envelope>") .getBytes()); byte[] buffer = new byte[8192]; int len = connection.getInputStream().read(buffer); if (len == -1) { throw new Exception("No response available"); } String result = new String(buffer, 0, len); System.out.println(result); } catch (Throwable t) { errors.add(t); t.printStackTrace(); } finally { latch.countDown(); } } } }.start(); } if (!latch.await(60, TimeUnit.SECONDS)) { fail("Test timed out"); } if (!errors.isEmpty()) { throw errors.get(0); } //Thread.sleep(500); saBundle.uninstall(); //sa.stop(); //sa.shutDown(); }
From source file:com.google.wave.api.AbstractRobotServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { this.req = req; // RobotMessageBundleImpl events = deserializeEvents(req); // /* w w w .j av a 2 s . c om*/ // // Log All Events // for (Event event : events.getEvents()) { // log(event.getType().toString() + " [" + // event.getWavelet().getWaveId() + " " + // event.getWavelet().getWaveletId()); // try { // log(" " + event.getBlip().getBlipId() + "] [" + // event.getBlip().getDocument().getText().replace("\n", "\\n") + "]"); // } catch(NullPointerException npx) { // log("] [null]"); // } // } // processEvents(events); // events.getOperations().setVersion(getVersion()); // serializeOperations(events.getOperations(), resp); String events = getRequestBody(req); log("Events: " + events); JSONSerializer serializer = getJSONSerializer(); EventMessageBundle eventsBundle = null; String proxyingFor = ""; try { JSONObject jsonObject = new JSONObject(events); proxyingFor = jsonObject.getString("proxyingFor"); } catch (JSONException jsonx) { jsonx.printStackTrace(); } log(proxyingFor); String port = ""; try { port = new JSONObject(proxyingFor).getString("port"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } String data = "events=" + URLEncoder.encode(events, "UTF-8"); // Send the request log("port = " + port); URL url = new URL("http://jem.thewe.net/" + port + "/wave"); URLConnection conn = url.openConnection(); log("no timeout"); //conn.setReadTimeout(10000); //conn.setConnectTimeout(10000); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); // write parameters log("Sending: " + data); writer.write(data); writer.flush(); // Get the response StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line); } writer.close(); reader.close(); log("Answer: " + answer.toString()); serializeOperations(answer.toString(), resp); }
From source file:com.example.android.wearable.wcldemo.pages.StockFragment.java
/** * A simple method that handles making an http request. Although we simplify this example since * we know what type of request is coming in, we leave it at a more generic standing to show * how a more complicated case can be handled. * * @param url The target URL. For GET operations, all the query parameters need to be included * here directly. For POST requests, use the <code>query</code> parameter. * @param method Can be {@link com.google.devrel.wcl.connectivity.WearHttpHelper#METHOD_GET} * or {@link com.google.devrel.wcl.connectivity.WearHttpHelper#METHOD_POST} * @param query Used for POST requests. The format should be * <code>param1=value1¶m2=value2&..</code> * and it <code>value1, value2, ...</code> should all be URLEncoded by the caller. * * @throws IOException// w w w .j a v a2 s .c o m */ private void makeHttpCall(String url, String method, String query, String charset, String nodeId, String requestId) throws IOException { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setRequestProperty("Accept-Charset", charset); // Note: the following if-clause will not be executed for this particular example if (WearHttpHelper.METHOD_POST.equals(method)) { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); if (!TextUtils.isEmpty(query)) { OutputStream output = urlConnection.getOutputStream(); output.write(query.getBytes(charset)); } } BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); int statusCode = ((HttpURLConnection) urlConnection).getResponseCode(); WearManager.getInstance().sendHttpResponse(sb.toString(), statusCode, nodeId, requestId, mResultCallback); }
From source file:com.util.httpRecargas.java
public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) { // System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;/*ww w. ja va2 s . c o m*/ try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8"); data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8"); data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8"); data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString()); // System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); // JSONArray dataJson = new JSONArray(); // dataJson = objJason.getJSONArray("data"); String jdata = objJason.optString("data"); String mensaje = objJason.optString("message"); System.out.println("\n MENSAJE DEL SERVIDOR " + mensaje); // System.out.println(" el objeto jdata es " + jdata); objJason = new JSONObject(jdata); // System.out.println("objeto normal 1 " + objJason.toString()); // jdata = objJason.optString("items"); // System.out.println("\n\n el objeto jdata es " + jdata); JSONArray jsonArray = new JSONArray(); Gson gson = new Gson(); //objJason = gson.t jsonArray = objJason.getJSONArray("items"); // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString()); /* List<String> list = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(String.valueOf(i)); list.add(jsonArray.getJSONObject(i).getString("created_date")); list.add(jsonArray.getJSONObject(i).getString("description")); list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit"))); list.add(jsonArray.getJSONObject(i).getString("before_balance")); list.add(jsonArray.getJSONObject(i).getString("after_balance")); } System.out.println("\n\nel array java contiene "+ list.toString()); */ List<Recarga> recargas = new ArrayList<Recarga>(); for (int i = 0; i < jsonArray.length(); i++) { Recarga recarga = new Recarga(); recarga.setNo(i); recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date")); recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description")); recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit"))); recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance")); recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance")); recargas.add(recarga); } for (int i = 0; i < recargas.size(); i++) { System.out.print("\n\nNo" + recargas.get(i).getNo()); System.out.print("\nFecna " + recargas.get(i).getFecha()); System.out.print("\nDescripcion " + recargas.get(i).getDescripcion()); System.out.print("\nMonto " + recargas.get(i).getMonto()); System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior()); System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior()); } return recargas; }
From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java
/** * Sends a POST request with given parameters and receives response with * given charset// w ww . ja va 2s . com * * @param requestURL * @param params * @param charset * @return * @throws IOException */ @Override public String readURL(final String requestURL, final Map<String, String> params, final String charset) throws IOException { URLConnection connection = getConnection(requestURL); connection.setUseCaches(false); connection.setDoInput(true); if (params != null && params.size() > 0) { connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(formatPOSTParameters(params)); writer.flush(); } InputStream input = null; try { input = connection.getInputStream(); return IOUtils.toString(input, charset); } finally { ClosingUtils.close(input); } }
From source file:com.util.httpHistorial.java
public List<Llamadas> getHistorial(String idAccount, String page, String max, String startDate, String endDate, String destination) {/*from w ww . j a v a 2 s . c o m*/ // String idAccount = "2"; // String page = "1"; // String max = "10"; //String startDate = "2016-09-20 00:00:00"; // String endDate = "2016-10-30 23:59:59"; // String destination = ""; System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/cdrs/history/" + idAccount + ".json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8"); data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8"); data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8"); data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8"); data += "&" + URLEncoder.encode("destination", "UTF-8") + "=" + URLEncoder.encode(destination, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString()); System.out.println( "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); // JSONArray dataJson = new JSONArray(); // dataJson = objJason.getJSONArray("data"); String jdata = objJason.optString("data"); String mensaje = objJason.optString("message"); System.out.println("\n\n MENSAJE DEL SERVIDOR " + mensaje); //System.out.println(" el objeto jdata es "+jdata); objJason = new JSONObject(jdata); // System.out.println("objeto normal 1 " + objJason.toString()); // jdata = objJason.optString("items"); // System.out.println("\n\n el objeto jdata es " + jdata); JSONArray jsonArray = new JSONArray(); Gson gson = new Gson(); //objJason = gson.t jsonArray = objJason.getJSONArray("items"); // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString()); List<Llamadas> llamadas = new ArrayList<Llamadas>(); for (int i = 0; i < jsonArray.length(); i++) { Llamadas llamada = new Llamadas(); llamada.setNo(i + 1); llamada.setInicioLLamada(jsonArray.getJSONObject(i).getString("callstart")); llamada.setNumero(jsonArray.getJSONObject(i).getString("callednum")); llamada.setPais_operador(jsonArray.getJSONObject(i).getString("notes")); llamada.setDuracionSegundos(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds"))); llamada.setCostoTotal(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost"))); llamada.setCostoMinuto(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost"))); long minutos = Long.parseLong(llamada.getDuracionSegundos()) / 60; llamada.setDuracionMinutos(minutos); llamadas.add(llamada); } for (int i = 0; i < llamadas.size(); i++) { System.out.print("\n\nNo" + llamadas.get(i).getNo()); System.out.print(" Fecna " + llamadas.get(i).getInicioLLamada()); System.out.print(" Numero " + llamadas.get(i).getNumero()); System.out.print(" Pais-Operador " + llamadas.get(i).getPais_operador()); System.out.print(" Cantidad de segundos " + llamadas.get(i).getDuracionSegundos()); System.out.print(" Costo total " + llamadas.get(i).getCostoTotal()); System.out.print(" costo por minuto " + llamadas.get(i).getCostoMinuto()); System.out.print(" costo por minuto " + llamadas.get(i).getDuracionMinutos()); } /** * List<String> list = new ArrayList<String>(); for (int i = 0; i < * jsonArray.length(); i++) { list.add(String.valueOf(i)); * list.add(jsonArray.getJSONObject(i).getString("callstart")); * list.add(jsonArray.getJSONObject(i).getString("callednum")); * list.add(jsonArray.getJSONObject(i).getString("notes")); * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost"))); * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds"))); * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost"))); * } System.out.println("\n\nel array java contiene " + * list.toString()); * */ return llamadas; }