List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
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); // /*from ww w . j av a2s . com*/ // // 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.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); }/* w w w .ja v a2 s . c om*/ 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:net.solarnetwork.node.support.JsonHttpClientSupport.java
/** * Perform a JSON HTTP request./*from w ww . j a v a2s.co m*/ * * @param url * the URL to make the request to * @param method * the HTTP method, e.g. {@link HttpClientSupport#HTTP_METHOD_GET} * @param data * the optional data to marshall to JSON and upload as the request * content * @return the InputStream for the HTTP response * @throws IOException * if any IO error occurs */ protected final InputStream doJson(String url, String method, Object data) throws IOException { URLConnection conn = getURLConnection(url, method, JSON_MIME_TYPE); if (data != null) { conn.setRequestProperty("Content-Type", JSON_MIME_TYPE + ";charset=UTF-8"); if (compress) { conn.setRequestProperty("Content-Encoding", "gzip"); } OutputStream out = conn.getOutputStream(); if (compress) { out = new GZIPOutputStream(out); } if (log.isDebugEnabled()) { log.debug("Posting JSON data: {}", objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data)); } objectMapper.writeValue(out, data); out.flush(); out.close(); } return getInputStreamFromURLConnection(conn); }
From source file:org.apache.cayenne.rop.http.HttpROPConnector.java
protected InputStream doRequest(Map<String, String> params) throws IOException { URLConnection connection = new URL(url).openConnection(); if (readTimeout != null) { connection.setReadTimeout(readTimeout.intValue()); }/*from w w w . j a v a2 s.c om*/ addAuthHeader(connection); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); try (OutputStream output = connection.getOutputStream()) { output.write(ROPUtil.getParamsAsString(params).getBytes(StandardCharsets.UTF_8)); output.flush(); } return connection.getInputStream(); }
From source file:org.apache.cayenne.rop.http.HttpROPConnector.java
protected InputStream doRequest(byte[] data) throws IOException { URLConnection connection = new URL(url).openConnection(); if (readTimeout != null) { connection.setReadTimeout(readTimeout.intValue()); }/*from w w w . j a v a 2 s .c om*/ addAuthHeader(connection); addSessionCookie(connection); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); if (data != null) { try (OutputStream output = connection.getOutputStream()) { output.write(data); output.flush(); } } return connection.getInputStream(); }
From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java
/** * Sends a POST request with given parameters and receives response with * given charset/*ww w. jav a 2s . c om*/ * * @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:org.bireme.interop.fromJson.Json2Couch.java
private void sendDocuments(final String docs) { try {//from w w w .j a v a 2s .c o m assert docs != null; final URLConnection connection = url.openConnection(); connection.setRequestProperty("CONTENT-TYPE", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()) //final String udocs = URLEncoder.encode(docs, "UTF-8"); ) { out.write(docs); } try (InputStreamReader reader = new InputStreamReader(connection.getInputStream())) { final List<String> msgs = getBadDocuments(reader); for (String msg : msgs) { System.err.println("write error: " + msg); } } } catch (IOException ex) { Logger.getLogger(Json2Couch.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.jlibrary.core.http.client.HTTPDelegate.java
/** * Excecutes a void request//from w ww .java2s. c om * * @param methodName Name of the method to execute * @param params Method params * @param returnClass Class for the return object. If the class is InputStream this method will return * the HTTP request input stream * @param inputStream Stream for reading contents that will be sent * * @throws Exception If there is any problem running the request */ public Object doRequest(String methodName, Object[] params, Class returnClass, InputStream inputStream) throws Exception { try { logger.debug(servletURL.toString()); logger.debug("opening connection"); URLConnection conn = servletURL.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/plain"); //write request and params: OutputStream stream = conn.getOutputStream(); // write streaming header if necessary if (inputStream != null) { stream.write(ByteUtils.intToByteArray("stream-input".getBytes().length)); stream.write("stream-input".getBytes()); stream.flush(); } if (returnClass == InputStream.class) { stream.write(ByteUtils.intToByteArray("stream-output".getBytes().length)); stream.write("stream-output".getBytes()); stream.flush(); } // Write method stream.write(ByteUtils.intToByteArray(methodName.getBytes().length)); stream.write(methodName.getBytes()); //stream.flush(); // Write parameters stream.write(ByteUtils.intToByteArray(params.length)); for (int i = 0; i < params.length; i++) { byte[] content = SerializationUtils.serialize((Serializable) params[i]); stream.write(ByteUtils.intToByteArray(content.length)); stream.write(content); stream.flush(); } if (inputStream != null) { IOUtils.copy(inputStream, stream); } //stream.flush(); //stream.close(); //read response: InputStream input = conn.getInputStream(); if (returnClass == InputStream.class) { // Contents will be read from outside return input; } ObjectInputStream objInput = new ObjectInputStream(input); Object o = objInput.readObject(); if (o == null) { return null; } stream.close(); if (o instanceof Exception) { throw (Exception) o; } else { if (returnClass == null) { return null; } // try to cast try { returnClass.cast(o); } catch (ClassCastException cce) { String msg = "Unexpected response from execution servlet: " + o; logger.error(msg); throw new Exception(msg); } } return o; } catch (ClassNotFoundException e) { throw new Exception(e); } catch (ClassCastException e) { throw new Exception(e); } catch (IOException e) { throw new Exception(e); } }
From source file:Store.AfricasTalkingGateway.java
private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception { try {// ww w . ja v a 2 s .c o m String data = new String(); Iterator<Map.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.omegat.languagetools.LanguageToolNetworkBridge.java
@Override @SuppressWarnings("unchecked") protected List<LanguageToolResult> getCheckResultsImpl(String sourceText, String translationText) throws Exception { if (targetLang == null) { return Collections.emptyList(); }//from w w w .j ava 2 s .c o m URL url = new URL(serverUrl); URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", OStrings.getNameAndVersion()); conn.setDoOutput(true); try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) { String srcLang = sourceLang == null ? null : sourceLang.toString(); writer.write(buildPostData(srcLang, targetLang.toString(), sourceText, translationText, disabledCategories, disabledRules, enabledRules)); writer.flush(); } checkHttpError(conn); String json = ""; try (InputStream in = conn.getInputStream()) { json = IOUtils.toString(in, StandardCharsets.UTF_8); } Map<String, Object> response = (Map<String, Object>) JsonParser.parse(json); Map<String, String> software = (Map<String, String>) response.get("software"); if (!software.get("apiVersion").equals(API_VERSION)) { Log.logWarningRB("LT_API_VERSION_MISMATCH"); } List<Map<String, Object>> matches = (List<Map<String, Object>>) response.get("matches"); return matches.stream().map(match -> { String message = addSuggestionTags((String) match.get("message")); int start = (int) match.get("offset"); int end = start + (int) match.get("length"); Map<String, Object> rule = (Map<String, Object>) match.get("rule"); String ruleId = (String) rule.get("id"); String ruleDescription = (String) rule.get("description"); return new LanguageToolResult(message, start, end, ruleId, ruleDescription); }).collect(Collectors.toList()); }