List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:org.omegat.languagetools.LanguageToolNetworkBridge.java
/** * Try to talk with LT server and return result *//*ww w . j av a 2 s . c o m*/ static boolean testServer(String testUrl) { if (testUrl.trim().toLowerCase(Locale.ENGLISH).startsWith("https://languagetool.org/api/v2/check")) { // Blacklist the official LanguageTool public API specifically // because this is what users are most likely to try, but they ask // not to send automated requests: // http://wiki.languagetool.org/public-http-api return false; } try { URL url = new URL(testUrl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) { // Supply a dummy disabled category to force the server to take // its configuration from this query only, not any server-side // config. writer.write(buildPostData(null, "en-US", null, "Test", "FOO", null, null)); writer.flush(); } checkHttpError(conn); try (InputStream in = conn.getInputStream()) { String response = IOUtils.toString(in, StandardCharsets.UTF_8); if (response.contains("<?xml")) { Log.logErrorRB("LT_WRONG_FORMAT_RESPONSE"); return false; } else { return true; } } } catch (Exception e) { Log.log(e); return false; } }
From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java
public static int sendRequestToRetriveHeaders(String addUrl, String query, String contentType) 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", contentType + ";charset=" + charset); OutputStream output = null;/*from w ww . j a v a 2s. c om*/ 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; int responseCode = httpConn.getResponseCode(); return responseCode; }
From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java
public static int sendRequestToRetriveHeaders(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 ww . ja v a 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"); } } } HttpURLConnection httpConn = (HttpURLConnection) connection; int responseCode = httpConn.getResponseCode(); return responseCode; }
From source file:com.adrguides.utils.HTTPUtils.java
public static InputStream openAddress(Context context, URL url) throws IOException { if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) { return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15 } else {/* w ww . j av a 2 s . c o m*/ URLConnection urlconn = url.openConnection(); urlconn.setReadTimeout(10000 /* milliseconds */); urlconn.setConnectTimeout(15000 /* milliseconds */); urlconn.setAllowUserInteraction(false); urlconn.setDoInput(true); urlconn.setDoOutput(false); if (urlconn instanceof HttpURLConnection) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responsecode = connection.getResponseCode(); if (responsecode != HttpURLConnection.HTTP_OK) { throw new IOException("Http response code returned:" + responsecode); } } return urlconn.getInputStream(); } }
From source file:de.akquinet.android.androlog.reporter.PostReporter.java
/** * Executes the given request as a HTTP POST action. * * @param url// ww w. j a v a 2 s . c o m * the url * @param params * the parameter * @return the response as a String. * @throws IOException * if the server cannot be reached */ public static void post(URL url, String params) throws IOException { URLConnection conn = url.openConnection(); if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); } OutputStreamWriter writer = null; try { conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8")); // write parameters writer.write(params); writer.flush(); } finally { if (writer != null) { writer.close(); } } }
From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java
public static OMElement sendXMLRequest(String addUrl, String query) throws MalformedURLException, IOException, XMLStreamException { 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;/* ww w . ja va2s . 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"); } } } 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(); } } OMElement omElement = AXIOMUtil.stringToOM(out); return omElement; }
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); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null;/* w w w. j av a 2s .co 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"); } } } 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.hortonworks.amstore.view.AmbariStoreHelper.java
@SuppressWarnings("restriction") public static String readStringFromUrl(String url, String username, String password) throws IOException { URLConnection connection = new URL(url).openConnection(); connection.setConnectTimeout(5000);// w w w . j a v a 2 s .c o m connection.setReadTimeout(5000); connection.setDoOutput(true); if (username != null) { String userpass = username + ":" + password; // TODO: Use apache commons instead. String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); connection.setRequestProperty("Authorization", basicAuth); } InputStream in = connection.getInputStream(); try { return IOUtils.toString(in, "UTF-8"); } finally { in.close(); } }
From source file:com.android.W3T.app.network.NetworkUtil.java
public static int attemptSendReceipt(String op, Receipt r) { // Here we may want to check the network status. checkNetwork();// w ww. j a va 2 s . co m try { JSONObject jsonstr = new JSONObject(); if (op.equals(METHOD_SEND_RECEIPT)) { // Add your data JSONObject basicInfo = new JSONObject(); basicInfo.put("store_account", r.getEntry(ENTRY_STORE_ACC));// store name basicInfo.put("currency_mark", r.getEntry(ENTRY_CURRENCY)); basicInfo.put("store_define_id", r.getEntry(ENTRY_RECEIPT_ID)); basicInfo.put("source", r.getEntry(ENTRY_SOURCE)); basicInfo.put("tax", r.getEntry(ENTRY_TAX)); // tax basicInfo.put("total_cost", r.getEntry(ENTRY_TOTAL)); // total price basicInfo.put("user_account", UserProfile.getUsername()); JSONObject receipt = new JSONObject(); receipt.put("receipt", basicInfo); receipt.put("items", r.getItemsJsonArray()); receipt.put("opcode", op); receipt.put("acc", UserProfile.getUsername()); jsonstr.put("json", receipt); } URL url = new URL(RECEIPT_OP_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // Must put "json=" here for server to decoding the data String data = "json=" + jsonstr.toString(); out.write(data); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String s = in.readLine(); System.out.println(s); if (Integer.valueOf(s) > 0) { return Integer.valueOf(s); } else return 0; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }
From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java
public static String get(String urlString, Hashtable<String, String[]> params) throws MetacatUtilException { try {// w ww . j a va 2s. c om URL url = new URL(urlString); URLConnection urlConn = url.openConnection(); urlConn.setDoOutput(true); PrintWriter pw = new PrintWriter(urlConn.getOutputStream()); String queryString = paramsToQuery(params); logMetacat.debug("Sending get request: " + urlString + "?" + queryString); pw.print(queryString); pw.close(); // get the input from the request BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); return sb.toString(); } catch (MalformedURLException mue) { throw new MetacatUtilException("URL error when contacting: " + urlString + " : " + mue.getMessage()); } catch (IOException ioe) { throw new MetacatUtilException("I/O error when contacting: " + urlString + " : " + ioe.getMessage()); } }