List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.telefonica.iot.perseo.Utils.java
/** * Makes an HTTP POST to an URL sending an body. The URL and body are * represented as String.//from ww w.jav a 2 s. c om * * @param urlStr String representation of the URL * @param content Styring representation of the body to post * * @return if the request has been accompished */ public static boolean DoHTTPPost(String urlStr, String content) { try { URL url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID)); urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD)); urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD)); urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD)); OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(), Charset.forName("UTF-8")); printout.write(content); printout.flush(); printout.close(); int code = urlConn.getResponseCode(); String message = urlConn.getResponseMessage(); logger.debug("action http response " + code + " " + message); if (code / 100 == 2) { InputStream input = urlConn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); for (String line; (line = reader.readLine()) != null;) { logger.info("action response body: " + line); } input.close(); return true; } else { logger.error("action response is not OK: " + code + " " + message); InputStream error = urlConn.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(error)); for (String line; (line = reader.readLine()) != null;) { logger.error("action error response body: " + line); } error.close(); return false; } } catch (MalformedURLException me) { logger.error("exception MalformedURLException: " + me); return false; } catch (IOException ioe) { logger.error("exception IOException: " + ioe); return false; } }
From source file:flexpos.restfulConnection.java
public static String postRESTful(String RESTfull_URL, String data) { String state = ""; try {//from w w w . j a v a 2s. c o m URL url = new URL(RESTfull_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request postRequest(connection, data); //Get Response state = postResponse(connection); if (connection != null) { connection.disconnect(); } } catch (Exception ex) { Logger.getLogger(restfulConnection.class.getName()).log(Level.SEVERE, null, ex); } return state; }
From source file:com.cnaude.mutemanager.UUIDFetcher.java
private static HttpURLConnection createConnection() throws Exception { URL url = new URL(PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false);/*from w ww. j a va 2 s .c o m*/ connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password.//from w ww. ja v a2s .c om * This is basically a standard OAuth2 password grant interaction. * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String password) { String token = null; try { Log.i(TAG, "Authenticating to: " + AUTH_URI); URL urlToRequest = new URL(AUTH_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("grant_type", "password")); params.add(new BasicNameValuePair("client_id", "CLIENT_ID")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); // Response body will look something like this: // { // "token_type": "bearer", // "access_token": "0dd18fd38e84fb40e9e34b1f82f65f333225160a", // "expires_in": 3600 // } JSONObject jresp = new JSONObject(new JSONTokener(response)); token = jresp.getString("access_token"); } else { Log.e(TAG, "Error authenticating"); token = null; } } catch (Exception e) { e.printStackTrace(); } finally { Log.v(TAG, "getAuthtoken completing"); } return token; }
From source file:com.pureinfo.srm.outlay.action.SearchCheckCodeAction.java
/** * /*from ww w . j a v a 2 s . com*/ * @param strUrl * @param strPostRequest * @return */ public static String getPageContent(String strUrl, String strPostRequest) { // StringBuffer buffer = new StringBuffer(); System.setProperty("sun.net.client.defaultConnectTimeout", "5000"); System.setProperty("sun.net.client.defaultReadTimeout", "5000"); try { URL newUrl = new URL(strUrl); HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection(); //POST if (strPostRequest.length() > 0) { hConnect.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream()); out.write(strPostRequest); out.flush(); out.close(); } // BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream())); int ch; for (int length = 0; (ch = rd.read()) > -1; length++) buffer.append((char) ch); rd.close(); hConnect.disconnect(); return buffer.toString().trim(); } catch (Exception e) { // return ":"; return null; } finally { buffer.setLength(0); } }
From source file:io.github.retz.web.JobRequestRouter.java
public static boolean statHTTPFile(String url, String name) { String addr = url.replace("files/browse", "files/download") + "%2F" + maybeURLEncode(name); HttpURLConnection conn = null; try {//from w w w.j a v a2 s. c o m conn = (HttpURLConnection) new URL(addr).openConnection(); conn.setRequestMethod("HEAD"); conn.setDoOutput(false); LOG.debug(conn.getResponseMessage()); return conn.getResponseCode() == 200 || conn.getResponseCode() == 204; } catch (IOException e) { LOG.debug("Failed to fetch {}: {}", addr, e.toString()); return false; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:Main.java
public static String readTextFromURL(String urlString) throws IOException { HttpURLConnection urlConnection = null; URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setDoOutput(true); urlConnection.connect();/*from w ww . java 2s . co m*/ BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); char[] buffer = new char[1024]; String jsonString = new String(); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); return sb.toString(); }
From source file:com.screenslicer.core.util.Email.java
public static void sendResults(EmailExport export) { if (WebApp.DEV) { return;// ww w .ja v a 2s. c om } Map<String, Object> params = new HashMap<String, Object>(); params.put("key", Config.instance.mandrillKey()); List<Map<String, String>> to = new ArrayList<Map<String, String>>(); for (int i = 0; i < export.recipients.length; i++) { to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i], export.recipients[i].split("@")[0], "to")); } List<Map<String, String>> attachments = new ArrayList<Map<String, String>>(); for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) { attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()), entry.getKey(), Base64.encodeBase64String(entry.getValue()))); } params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers", "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.", "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title, Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments)); params.put("async", true); HttpURLConnection conn = null; String resp = null; Log.info("Sending email: " + export.title, false); try { conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json") .openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0"); String data = CommonUtil.gson.toJson(params, CommonUtil.objectType); byte[] bytes = data.getBytes("utf-8"); conn.setRequestProperty("Content-Length", "" + bytes.length); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); resp = IOUtils.toString(conn.getInputStream(), "utf-8"); if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) { Log.warn("Invalid/rejected email addreses"); } } catch (Exception e) { Log.exception(e); } }
From source file:com.intellectualcrafters.plot.uuid.UUIDFetcher.java
private static HttpURLConnection createConnection() throws Exception { final URL url = new URL(PROFILE_URL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false);//from w w w . ja va 2 s . c o m connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:com.arellomobile.android.push.utils.NetworkUtils.java
public static NetworkResult makeRequest(Map<String, Object> data, String methodName) throws Exception { NetworkResult result = new NetworkResult(500, null); OutputStream connectionOutput = null; InputStream inputStream = null; try {//w w w.j a v a2 s . c om String urlString = NetworkUtils.BASE_URL + methodName; if (useSSL) urlString = NetworkUtils.BASE_URL_SECURE + methodName; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setDoOutput(true); JSONObject innerRequestJson = new JSONObject(); for (String key : data.keySet()) { innerRequestJson.put(key, data.get(key)); } JSONObject requestJson = new JSONObject(); requestJson.put("request", innerRequestJson); connection.setRequestProperty("Content-Length", String.valueOf(requestJson.toString().getBytes().length)); connectionOutput = connection.getOutputStream(); connectionOutput.write(requestJson.toString().getBytes()); connectionOutput.flush(); connectionOutput.close(); inputStream = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream dataCache = new ByteArrayOutputStream(); // Fully read data byte[] buff = new byte[1024]; int len; while ((len = inputStream.read(buff)) >= 0) { dataCache.write(buff, 0, len); } // Close streams dataCache.close(); String jsonString = new String(dataCache.toByteArray()).trim(); Log.w(TAG, "PushWooshResult: " + jsonString); JSONObject resultJSON = new JSONObject(jsonString); result.setData(resultJSON); result.setCode(resultJSON.getInt("status_code")); } finally { if (null != inputStream) { inputStream.close(); } if (null != connectionOutput) { connectionOutput.close(); } } return result; }