List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
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. ja va2 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:eu.europa.ec.markt.dss.applet.io.NativeHTTPDataLoader.java
@Override public InputStream post(String url, InputStream content) throws CannotFetchDataException { try {//from w w w.j ava 2s . c o m URLConnection connection = new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); OutputStream out = connection.getOutputStream(); IOUtils.copy(content, out); out.close(); return connection.getInputStream(); } catch (IOException ex) { throw new CannotFetchDataException(ex, url); } }
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. j a v a2 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:nl.ru.ai.projects.parrot.tools.TwitterAccess.java
/** * Uploads an image/*w w w. j a v a2s.c o m*/ * @param image The image to upload * @param tweet The text of the tweet that needs to be posted with the image */ public void uploadImage(byte[] image, String tweet) { if (!enabled) return; ByteArrayOutputStream baos = new ByteArrayOutputStream(); RenderedImage img = getImageFromCamera(image); try { ImageIO.write(img, "jpg", baos); URL url = new URL("http://api.imgur.com/2/upload.json"); String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()), "UTF-8"); data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("f9c4861fc0aec595e4a64dd185751d28", "UTF-8"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); StringBuffer buffer = new StringBuffer(); InputStreamReader isr = new InputStreamReader(conn.getInputStream()); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) buffer.append((char) ch); String imgURL = processJSON(buffer.toString()); setStatus(tweet + " " + imgURL, 100); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
From source file:org.jabsorb.client.URLConnectionSession.java
public JSONObject sendAndReceive(JSONObject message) { try {/* w w w . ja va 2s . com*/ URLConnection connection = url.openConnection(); connection.setDoOutput(true); // As per http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html Writer request = new OutputStreamWriter(connection.getOutputStream()); request.write(message.toString()); request.close(); // TODO the following sequence of reading a string out of output stream is too complicated // there must be a simpler way StringBuffer builder = new StringBuffer(1024); char[] buffer = new char[1024]; Reader reader = new InputStreamReader(connection.getInputStream()); while (true) { int bytesRead = reader.read(buffer); if (bytesRead < 0) break; builder.append(buffer, 0, bytesRead); } reader.close(); JSONTokener tokener = new JSONTokener(builder.toString()); Object rawResponseMessage = tokener.nextValue(); JSONObject responseMessage = (JSONObject) rawResponseMessage; if (responseMessage == null) throw new ClientError("Invalid response type - " + rawResponseMessage.getClass()); return responseMessage; } catch (IOException ex) { throw new ClientError(ex); } catch (JSONException ex) { throw new ClientError(ex); } }
From source file:com.google.ie.common.util.ReCaptchaUtility.java
/** * /*w w w. j a v a 2s. c om*/ * This method makes a post request to captcha server for verification of * captcha. * * @param postUrl the url of the server * @param postParameters the parameters making the post request * @return String the message from the server in response to the request * posted * @throws IOException */ private String sendPostRequest(String postUrl, String postParameters) throws IOException { OutputStream out = null; String message = null; InputStream in = null; try { URL url = new URL(postUrl); /* open connection with settings */ URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); /* open output stream */ out = urlConnection.getOutputStream(); out.write(postParameters.getBytes()); out.flush(); /* open input stream */ in = urlConnection.getInputStream(); /* get output */ ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; while (true) { int rc = in.read(buf); if (rc <= 0) break; bout.write(buf, 0, rc); } message = bout.toString(); /* close streams */ out.close(); in.close(); return message; } catch (IOException e) { LOG.error("Cannot load URL: " + e.getMessage()); out.close(); in.close(); return null; } }
From source file:de.liedtke.data.url.BasicDAOUrl.java
protected JSONObject requestUrl(final String daoName, final String methodName, final String jsonValue) throws JSONException { String jsonString = null;//from www . jav a2 s. c o m try { // Construct data final StringBuilder params = new StringBuilder(); params.append(URLEncoder.encode("daoName", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(daoName, Constants.UTF8)); params.append("&"); params.append(URLEncoder.encode("methodName", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(methodName, Constants.UTF8)); if (jsonValue != null) { params.append("&"); params.append(URLEncoder.encode("jsonValue", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(jsonValue, Constants.UTF8)); } params.append("&"); params.append(URLEncoder.encode("kind", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(ResultKind.JSON.toString(), Constants.UTF8)); // Send data URL url = new URL(address); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(params.toString()); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder sBuilder = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sBuilder.append(line); } jsonString = sBuilder.toString(); wr.close(); rd.close(); } catch (UnsupportedEncodingException e) { logger.warning("UnsupportedEncodingException occured: " + e.getMessage()); } catch (IOException e) { logger.warning("IOException occured: " + e.getMessage()); } JSONObject json = null; if (jsonString == null) { json = null; } else { json = new JSONObject(jsonString); } return json; }
From source file:org.jabsorb.ng.client.URLConnectionSession.java
public JSONObject sendAndReceive(JSONObject message) { try {// w w w. java 2 s.c om URLConnection connection = url.openConnection(); connection.setDoOutput(true); // As per // http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html Writer request = new OutputStreamWriter(connection.getOutputStream()); request.write(message.toString()); request.close(); // TODO the following sequence of reading a string out of output // stream is too complicated // there must be a simpler way StringBuffer builder = new StringBuffer(1024); char[] buffer = new char[1024]; Reader reader = new InputStreamReader(connection.getInputStream()); while (true) { int bytesRead = reader.read(buffer); if (bytesRead < 0) break; builder.append(buffer, 0, bytesRead); } reader.close(); JSONTokener tokener = new JSONTokener(builder.toString()); Object rawResponseMessage = tokener.nextValue(); JSONObject responseMessage = (JSONObject) rawResponseMessage; if (responseMessage == null) throw new ClientError("Invalid response type - " + rawResponseMessage.getClass()); return responseMessage; } catch (IOException ex) { throw new ClientError(ex); } catch (JSONException ex) { throw new ClientError(ex); } }
From source file:eu.europa.esig.dss.client.http.NativeHTTPDataLoader.java
@Override public byte[] post(String url, byte[] content) { OutputStream out = null;//from w ww. java 2 s.c om InputStream inputStream = null; byte[] result = null; try { URLConnection connection = new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); out = connection.getOutputStream(); IOUtils.write(content, out); inputStream = connection.getInputStream(); result = IOUtils.toByteArray(inputStream); } catch (IOException e) { throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(inputStream); } return result; }
From source file:org.trpr.platform.batch.impl.job.ha.service.SyncServiceImpl.java
/** * Generic method which is used to send a request from request String * @param data The POST request string/*from w w w . j ava 2 s . c om*/ * @param urlToConnect The URL of server * @return Response from server, empty string if no response received */ private String request(String data, String urlToConnect) { PrintWriter writer = null; OutputStream output = null; try { //Connecting.. URL url = new URL(urlToConnect); URLConnection conn = url.openConnection(); //POST method conn.setDoOutput(true); output = conn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, SyncServiceImpl.ENCODING), true); // true = Autoflush //Writing the response writer.println(data); //Reading the response BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String retline; String finalReturnValue = ""; while ((retline = reader.readLine()) != null) { finalReturnValue += retline; } return finalReturnValue; } catch (IOException e) { LOGGER.error("Exception while pushing request", e); } return "Unexpected exception. See log for details"; }