List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:org.wso2.esb.integration.common.utils.clients.JSONClient.java
private JSONObject sendRequest(String addUrl, String query) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null;/* w w w .j av a 2s . com*/ try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } JSONObject jsonObject = new JSONObject(out); return jsonObject; }
From source file:com.krawler.esp.handlers.APICallHandlerServiceImpl.java
@Override public JSONObject callApp(String appURL, JSONObject jData, String companyid, String action, boolean storeCall) { String requestData = (jData == null ? "" : jData.toString()); Apiresponse apires = null;/*from ww w .ja v a 2 s.c o m*/ if (storeCall) { apires = makePreEntry(companyid, requestData, action); } String res = "{success:false}"; InputStream iStream = null; String strSandbox = appURL + API_STRING; try { URL u = new URL(strSandbox); URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); java.io.PrintWriter pw = new java.io.PrintWriter(uc.getOutputStream()); pw.println("action=" + action + "&data=" + URLEncoder.encode(requestData, "UTF-8")); pw.close(); iStream = uc.getInputStream(); java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(iStream)); res = URLDecoder.decode(in.readLine(), "UTF-8"); in.close(); iStream.close(); } catch (IOException iex) { logger.warn("Remote API call for '" + strSandbox + "' failed because " + iex.getMessage()); } finally { if (iStream != null) { try { iStream.close(); } catch (Exception e) { } } } JSONObject resObj; try { resObj = new JSONObject(res); } catch (Exception ex) { logger.warn("Improper response from Remote API: " + res); resObj = new JSONObject(); try { resObj.put("success", false); } catch (Exception e) { } } if (storeCall) { makePostEntry(apires, res); } return resObj; }
From source file:org.wso2.esb.integration.common.utils.clients.JSONClient.java
private JSONObject sendRequest(String addUrl, String query, String action) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("SOAPAction", action); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null;/*from w w w . j a va 2s.c o m*/ try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } JSONObject jsonObject = new JSONObject(out); return jsonObject; }
From source file:CounterApp.java
public int getCount() throws Exception { java.net.URL url = new java.net.URL(servletURL); java.net.URLConnection con = url.openConnection(); if (sessionCookie != null) { con.setRequestProperty("cookie", sessionCookie); }/*from w w w .jav a 2 s . c o m*/ con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteOut); out.flush(); byte buf[] = byteOut.toByteArray(); con.setRequestProperty("Content-type", "application/octet-stream"); con.setRequestProperty("Content-length", "" + buf.length); DataOutputStream dataOut = new DataOutputStream(con.getOutputStream()); dataOut.write(buf); dataOut.flush(); dataOut.close(); DataInputStream in = new DataInputStream(con.getInputStream()); int count = in.readInt(); in.close(); if (sessionCookie == null) { String cookie = con.getHeaderField("set-cookie"); if (cookie != null) { sessionCookie = parseCookie(cookie); System.out.println("Setting session ID=" + sessionCookie); } } return count; }
From source file:com.alternatecomputing.jschnizzle.renderer.WebSequenceRenderer.java
public BufferedImage render(Diagram diagram) { String script = diagram.getScript(); if (script == null) { throw new RendererException("no script defined."); }/*from w w w . ja va2 s. c o m*/ String style = diagram.getStyle().getValue(); String baseURL = getBaseURL(); try { // build parameter string String data = "style=" + style + "&format=svg&message=" + URLEncoder.encode(script, "UTF-8"); // send the request URL url = new URL(baseURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); // write parameters 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(); JSONObject json = JSONObject.fromString(answer.toString()); HttpClient client = new HttpClient(); String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) { client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort)); } String getURI = baseURL + json.getString("img"); GetMethod getMethod = new GetMethod(getURI); client.executeMethod(getMethod); String svgContents = getMethod.getResponseBodyAsString(); getMethod.releaseConnection(); LOGGER.debug(svgContents); diagram.setEncodedImage(svgContents); TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgContents.getBytes())); BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder(); imageTranscoder.transcode(input, null); // log any errors to the UI console JSONArray errors = json.getJSONArray("errors"); for (int eIdx = 0; eIdx < errors.length(); ++eIdx) { LOGGER.error("JSON error: " + errors.getString(eIdx)); } return imageTranscoder.getBufferedImage(); } catch (MalformedURLException e) { throw new RendererException(e); } catch (IOException e) { throw new RendererException(e); } catch (TranscoderException e) { throw new RendererException(e); } }
From source file:TSAClient.java
private byte[] getTSAResponse(byte[] request) throws IOException { LOG.debug("Opening connection to TSA server"); // todo: support proxy servers URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true);//from www. j a va2 s . c o m connection.setRequestProperty("Content-Type", "application/timestamp-query"); LOG.debug("Established connection to TSA server"); if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) { connection.setRequestProperty(username, password); } // read response OutputStream output = null; try { output = connection.getOutputStream(); output.write(request); } finally { IOUtils.closeQuietly(output); } LOG.debug("Waiting for response from TSA server"); InputStream input = null; byte[] response; try { input = connection.getInputStream(); response = IOUtils.toByteArray(input); } finally { IOUtils.closeQuietly(input); } LOG.debug("Received response from TSA server"); return response; }
From source file:com.votingcentral.services.maxmind.MaxMindGeoLocationService.java
public MaxMindLocationTO getLocation(String ipAddress) { MaxMindLocationTO mto = new MaxMindLocationTO(); String specificData = data + FastURLEncoder.encode(ipAddress, "UTF-8"); URL url;/*from w w w. j a va 2 s . c o m*/ OutputStreamWriter wr = null; BufferedReader rd = null; try { url = new URL(surl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(specificData); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { String[] values = StringUtils.split(line, ","); int maxIndex = values.length - 1; if (maxIndex >= 0) { mto.setISO3166TwoLetterCountryCode(values[0]); } if (maxIndex >= 1) { mto.setRegionCode(values[1]); } if (maxIndex >= 2) { mto.setCity(values[2]); } if (maxIndex >= 3) { mto.setPostalCode(values[3]); } if (maxIndex >= 4) { mto.setLatitude(values[4]); } if (maxIndex >= 5) { mto.setLongitude(values[5]); } if (maxIndex >= 6) { mto.setMetropolitanCode(values[6]); } if (maxIndex >= 7) { mto.setAreaCode(values[7]); } if (maxIndex >= 8) { mto.setIsp(values[8]); } if (maxIndex >= 9) { mto.setOranization(values[9]); } if (maxIndex >= 10) { mto.setError(MaxMindErrorsEnum.get(values[10])); } } } catch (MalformedURLException e) { log.fatal("Issue calling Maxmind", e); mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR); } catch (IOException e) { log.fatal("Issue reading Maxmind", e); mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR); } finally { if (wr != null) { try { wr.close(); } catch (IOException e1) { log.fatal("Issue closing Maxmind", e1); mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR); } } if (rd != null) { try { rd.close(); } catch (IOException e1) { log.fatal("Issue closing Maxmind", e1); mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR); } } } return mto; }
From source file:com.github.beat.signer.pdf_signer.TSAClient.java
private byte[] getTSAResponse(byte[] request) throws IOException { LOGGER.debug("Opening connection to TSA server"); // FIXME: support proxy servers URLConnection connection = tsaInfo.getTsaUrl().openConnection(); connection.setDoOutput(true); connection.setDoInput(true);/*from w ww . ja va2 s. c o m*/ connection.setReadTimeout(CONNECT_TIMEOUT); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setRequestProperty("Content-Type", "application/timestamp-query"); // TODO set accept header LOGGER.debug("Established connection to TSA server"); String username = tsaInfo.getUsername(); char[] password = tsaInfo.getPassword(); if (StringUtils.isNotBlank(username) && password != null) { // FIXME this most likely wrong, e.g. set correct request property! // connection.setRequestProperty(username, password); } // read response sendRequest(request, connection); LOGGER.debug("Waiting for response from TSA server"); byte[] response = getResponse(connection); LOGGER.debug("Received response from TSA server"); return response; }
From source file:org.apache.uima.alchemy.annotator.AbstractAlchemyAnnotator.java
public void process(JCas aJCas) throws AnalysisEngineProcessException { // initialize service parameters initializeRuntimeParameters(aJCas);/*from w w w. j a v a 2 s . com*/ try { // open connection and send data URLConnection connection = this.alchemyService.openConnection(); connection.setDoOutput(true); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); writer.write(this.serviceParams); writer.flush(); writer.close(); InputStream bufByteIn = parseOutput(connection); // map alchemy api results to UIMA type system try { Results results = this.digester.parseAlchemyXML(bufByteIn); Validate.notNull(results); Validate.notNull(results.getStatus()); if (results.getStatus().equalsIgnoreCase(STATUS_OK)) { mapResultsToTypeSystem(results, aJCas); // annotations from results } else { throw new AlchemyCallFailedException(results.getStatus()); } } catch (Exception e) { throw new ResultDigestingException(e); } finally { bufByteIn.close(); } } catch (Exception e) { throw new AnalysisEngineProcessException(e); } }
From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java
public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) { //receives : apiEndPoint (https://api.test.sabre.com) //encodedCliAndSecret : base64Encode( base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) ) String strRet = null;// w w w. j ava 2 s . co m try { URL urlConn = new URL(apiEndPoint + "/v1/auth/token"); URLConnection conn = urlConn.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret); conn.setRequestProperty("Accept", "application/json"); //send request DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream()); dataOut.writeBytes("grant_type=client_credentials"); dataOut.flush(); dataOut.close(); //get response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strChunk = ""; StringBuilder sb = new StringBuilder(); while (null != ((strChunk = rd.readLine()))) sb.append(strChunk); //parse the token JSONObject respParser = new JSONObject(sb.toString()); strRet = respParser.getString("access_token"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return strRet; }