List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:jp.go.nict.langrid.serviceexecutor.google.GoogleTranslation.java
static void writeParameters(URLConnection c, Language sourceLang, Language targetLang, String... sources) throws IOException { StringBuilder b = new StringBuilder(); b.append("langpair=").append(sourceLang.getCode()).append("|").append(targetLang.getCode()); for (String s : sources) { b.append("&q=").append(URLEncoder.encode(s, "UTF-8")); }// w w w . j av a 2 s . c o m c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); c.getOutputStream().write(b.toString().getBytes("UTF-8")); }
From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java
/** * Send an HTTP(s) request with POST parameters. * //from w w w . j a va2 s .co m * @param parameters * @param url * @throws UnsupportedEncodingException * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ public static void doPost(Map<?, ?> parameters, URL url) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException { URLConnection cnx = getConnection(url); // Construct data StringBuilder dataBfr = new StringBuilder(); Iterator<?> iKeys = parameters.keySet().iterator(); while (iKeys.hasNext()) { if (dataBfr.length() != 0) { dataBfr.append('&'); } String key = (String) iKeys.next(); dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=') .append(URLEncoder.encode((String) parameters.get(key), "UTF-8")); } // POST data cnx.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream()); if (LOGGING.DEBUG) Log.d(LOG_TAG, "Posting crash report data"); wr.write(dataBfr.toString()); wr.flush(); wr.close(); if (LOGGING.DEBUG) Log.d(LOG_TAG, "Reading response"); BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream())); String line; int linecount = 0; while ((line = rd.readLine()) != null) { linecount++; if (linecount <= 2) { if (LOGGING.DEBUG) Log.d(LOG_TAG, line); } } rd.close(); }
From source file:com.beyondb.geocoding.BaiduAPI.java
public static Map<String, String> testPost(String x, String y) throws IOException { URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "=" + "&callback=renderReverse&location=" + x + "," + y + "&output=json"); URLConnection connection = url.openConnection(); /**/*from w ww. j ava2 s. com*/ * ??URLConnection?Web * URLConnection???Web??? */ connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); // remember to clean up out.flush(); out.close(); // ????? String res; InputStream l_urlStream; l_urlStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8")); StringBuilder sb = new StringBuilder(""); while ((res = in.readLine()) != null) { sb.append(res.trim()); } String str = sb.toString(); System.out.println(str); Map<String, String> map = null; if (StringUtils.isNotEmpty(str)) { int addStart = str.indexOf("formatted_address\":"); int addEnd = str.indexOf("\",\"business"); if (addStart > 0 && addEnd > 0) { String address = str.substring(addStart + 20, addEnd); map = new HashMap<String, String>(); map.put("address", address); return map; } } return null; }
From source file:org.wso2.connector.integration.bloggerV3.ConnectorIntegrationUtil.java
public static JSONObject sendRequestWithAcceptHeader(String addUrl, String query) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);/*from ww w. j a va 2 s .c o m*/ connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null; 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"); } } } HttpURLConnection httpConn = (HttpURLConnection) connection; InputStream response; if (httpConn.getResponseCode() >= 400) { response = httpConn.getErrorStream(); } else { response = connection.getInputStream(); } String out = "{}"; 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)); } if (!sb.toString().trim().isEmpty()) { out = sb.toString(); } } JSONObject jsonObject = new JSONObject(out); return jsonObject; }
From source file:com.beyondb.geocoding.BaiduAPI.java
public static String getPointByAddress(String address, String city) throws IOException { String resultPoint = ""; try {//from w w w. j a v a 2s.c o m URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=xml&address=" + address + "&" + city); URLConnection connection = url.openConnection(); /** * ??URLConnection?Web * URLConnection???Web??? */ connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); // remember to clean up out.flush(); out.close(); // ????? String res; InputStream l_urlStream; l_urlStream = connection.getInputStream(); if (l_urlStream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8")); StringBuilder sb = new StringBuilder(""); while ((res = in.readLine()) != null) { sb.append(res.trim()); } String str = sb.toString(); System.out.println(str); Document doc = DocumentHelper.parseText(str); // XML Element rootElt = doc.getRootElement(); // ? // System.out.println("" + rootElt.getName()); // ?? Element resultElem = rootElt.element("result"); if (resultElem.hasContent()) { Element locationElem = resultElem.element("location"); Element latElem = locationElem.element("lat"); // System.out.print("lat:"+latElem.getTextTrim()+","); Element lngElem = locationElem.element("lng"); // System.out.println("lng:"+lngElem.getTextTrim()); resultPoint = lngElem.getTextTrim() + "," + latElem.getTextTrim(); } else { System.out.println("can't compute the coor"); resultPoint = " , "; } } else { resultPoint = " , "; } } catch (DocumentException ex) { Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex); } return resultPoint; }
From source file:org.intermine.api.mines.FriendlyMineQueryRunner.java
/** * Run a query via the web service//from w w w .j a va 2 s .c o m * * @param urlString url to query * @return reader */ public static BufferedReader runWebServiceQuery(String urlString) { if (StringUtils.isEmpty(urlString)) { return null; } BufferedReader reader = null; try { if (!urlString.contains("?")) { // GET URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); LOG.info("FriendlyMine URL (GET) " + urlString); } else { // POST String[] params = urlString.split("\\?"); String newUrlString = params[0]; String queryString = params[1]; URL url = new URL(newUrlString); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryString); wr.flush(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); LOG.info("FriendlyMine URL (POST) " + urlString); } return reader; } catch (Exception e) { LOG.info("Unable to access " + urlString + " exception: " + e.getMessage()); return null; } }
From source file:BihuHttpUtil.java
public static String doHttpPost(String xmlInfo, String URL) { System.out.println("??:" + xmlInfo); byte[] xmlData = xmlInfo.getBytes(); InputStream instr = null;// w w w. j a v a2s .c o m java.io.ByteArrayOutputStream out = null; try { URL url = new URL(URL); URLConnection urlCon = url.openConnection(); urlCon.setDoOutput(true); urlCon.setDoInput(true); urlCon.setUseCaches(false); urlCon.setRequestProperty("Content-Type", "text/xml"); urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length)); System.out.println(String.valueOf(xmlData.length)); DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream()); printout.write(xmlData); printout.flush(); printout.close(); instr = urlCon.getInputStream(); byte[] bis = IOUtils.toByteArray(instr); String ResponseString = new String(bis, "UTF-8"); if ((ResponseString == null) || ("".equals(ResponseString.trim()))) { System.out.println(""); } System.out.println("?:" + ResponseString); return ResponseString; } catch (Exception e) { e.printStackTrace(); return "0"; } finally { try { out.close(); instr.close(); } catch (Exception ex) { return "0"; } } }
From source file:org.motechproject.mmnaija.web.util.HTTPCommunicator.java
public static String doPost(String serviceUrl, String queryString) { URLConnection connection = null; try {/*from w w w.j a va 2 s .c o m*/ URL url = new URL(serviceUrl); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); // Open the connection connection = url.openConnection(); connection.setDoInput(true); connection.setUseCaches(false); // Disable caching the document connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Content-Type", "text/html"); OutputStreamWriter writer = null; log.info("About to write"); try { if (null != connection.getOutputStream()) { writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(queryString); // Write POST query } else { log.warn("connection Null"); } // string. } catch (ConnectException ex) { log.warn("Exception : " + ex); // ex.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (Exception lg) { log.warn("Exception lg: " + lg.toString()); //lg.printStackTrace(); } } } InputStream in = connection.getInputStream(); // StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "utf-8"); String theString = writer.toString(); return theString; } catch (Exception e) { //e.printStackTrace(); log.warn("Error URL " + e.toString()); return ""; } }
From source file:com.moviejukebox.plugin.OpenSubtitlesPlugin.java
private static String sendRPC(String xml) throws IOException { StringBuilder str = new StringBuilder(); String strona = OS_DB_SERVER; String logowanie = xml;/*from w ww . ja va 2 s .co m*/ URL url = new URL(strona); URLConnection connection = url.openConnection(); connection.setRequestProperty("Connection", "Close"); // connection.setRequestProperty("Accept","text/html"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(Boolean.TRUE); connection.getOutputStream().write(logowanie.getBytes("UTF-8")); try (Scanner in = new Scanner(connection.getInputStream())) { while (in.hasNextLine()) { str.append(in.nextLine()); } } ((HttpURLConnection) connection).disconnect(); return str.toString(); }
From source file:net.daboross.bukkitdev.skywars.gist.GistReport.java
public static String gistText(Logger logger, String text) { URL postUrl;/*from w w w . j a v a2s . co m*/ try { postUrl = new URL("https://api.github.com/gists"); } catch (MalformedURLException ex) { logger.log(Level.FINE, "Non severe error encoding api.github.com URL", ex); return null; } URLConnection connection; try { connection = postUrl.openConnection(); } catch (IOException ex) { logger.log(Level.FINE, "Non severe error opening api.github.com connection", ex); return null; } connection.setDoOutput(true); connection.setDoInput(true); JSONStringer outputJson = new JSONStringer(); try { outputJson.object().key("description").value("SkyWars debug").key("public").value("false").key("files") .object().key("report.md").object().key("content").value(text).endObject().endObject() .endObject(); } catch (JSONException ex) { logger.log(Level.FINE, "Non severe error while writing report", ex); return null; } String jsonOuptutString = outputJson.toString(); try (OutputStream outputStream = connection.getOutputStream()) { try (OutputStreamWriter requestWriter = new OutputStreamWriter(outputStream)) { requestWriter.append(jsonOuptutString); requestWriter.close(); } } catch (IOException ex) { logger.log(Level.FINE, "Non severe error writing report", ex); return null; } JSONObject inputJson; try { inputJson = new JSONObject(readConnection(connection)); } catch (JSONException | IOException unused) { logger.log(Level.FINE, "Non severe error while reading response for report.", unused); return null; } String resultUrl = inputJson.optString("html_url", null); return resultUrl == null ? null : shortenURL(logger, resultUrl); }