List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) { try {/*from ww w . j a va 2 s .co m*/ HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); assembleMultipartFiles(out, vars, files); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (UnsupportedEncodingException e) { return "Encoding exception: " + e; } catch (IOException e) { return "IOException: " + e; } catch (IllegalStateException e) { return "IllegalState: " + e; } }
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean put(String bucketName, String objectKey, byte[] data, String contentType, boolean isPublic, String awsAccessId, String awsSecretKey) throws IOException { final byte[] md5Raw = MD5Util.md5(data); final String md5Base64 = Base64.encodeBase64String(md5Raw).trim(); final String md5Hex = MD5Util.toHex(md5Raw); final String date = getDate(); final String payloadStr = isPublic ? PUT_PAYLOAD_PUBLIC : PUT_PAYLOAD_PRIVATE; final String payload = String.format(payloadStr, md5Base64, contentType, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); final URL url = new URL(String.format(S3_URL, bucketName, objectKey)); OutputStream out = null;// w w w . j a v a 2 s . c om HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-MD5", md5Base64); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Date", date); if (isPublic) { // If we don't send this header, the object will be private by default conn.setRequestProperty("x-amz-acl", "public-read"); } conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); out = new BufferedOutputStream(conn.getOutputStream()); IOUtils.copy(new ByteArrayInputStream(data), out); out.flush(); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error uploading file: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } String etag = conn.getHeaderField("ETag"); etag = etag != null ? etag.replaceAll("\"", "") : null;// Remove quotes if (!md5Hex.equals(etag)) { log.severe("ETag comparison failed. Response ETag: " + etag + "Locally computed MD5: " + md5Hex); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(out); } }
From source file:no.ntnu.wifimanager.ServerUtilities.java
/** * Issue a POST request to server.// ww w . ja v a 2 s . c o m * * @param serverUrl POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType) throws IOException { URL url; try { url = new URL(serverUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + serverUrl); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(LOG_TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip + "&format=xml"); //URL url = new URL("http://ipinfodb.com/ip_query.php"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true);/*from w w w . j a va2s . c om*/ urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String theString = writer.toString(); Debug.logInfo("Get user position by IP stream is = ", theString); Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("stream", theString); return paramOut; }
From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java
/** * Makes a get request to the given url and returns the json object * @param sessionId// w ww .j ava 2 s . c o m * @param url * @return * @throws MalformedURLException * @throws IOException */ public static JSONArray makeGetRequest(String sessionId, String url) throws MalformedURLException, IOException { URL endpoint = new URL(url); HttpURLConnection urlc = (HttpURLConnection) endpoint.openConnection(); urlc.setRequestProperty("Authorization", "OAuth " + sessionId); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); String output = OauthHelperUtils.readInputStream(urlc.getInputStream()); urlc.disconnect(); Object json = JSONValue.parse(output); JSONArray jsonArr = (JSONArray) json; return jsonArr; }
From source file:neal.http.impl.httpstack.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, HttpErrorCollection.AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body);/*www .ja v a 2s.c o m*/ out.close(); } }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
private static HttpURLConnection makeGetConnection(URL url, byte[] bytes) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false);/*from ww w . j a v a 2s . c o m*/ conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); return conn; }
From source file:com.android.volley.toolbox.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body);//from w w w.j a va 2 s . c o m out.close(); } }
From source file:bluevia.SendSMS.java
public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) { try {//from ww w .jav a2s .c om Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount"); if (blueviaAccount != null) { String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key"); String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret"); String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key"); String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); consumer.setTokenWithSecret(access_key, access_secret); URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1"); HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); request.setRequestProperty("Content-Type", "application/json"); request.setRequestMethod("POST"); request.setDoOutput(true); consumer.sign(request); request.connect(); String smsTemplate = "{\"smsText\": {\n \"address\": {\"phoneNumber\": \"%s\"},\n \"message\": \"%s\",\n \"originAddress\": {\"alias\": \"%s\"},\n}}"; String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key); OutputStream os = request.getOutputStream(); os.write(smsMsg.getBytes()); os.flush(); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_CREATED) log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message)); else log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage())); } else log.warning("BlueVia Account seems to be not configured!"); } catch (Exception e) { log.severe(String.format("Exception sending SMS: %s", e.getMessage())); } }
From source file:com.onesignal.OneSignalRestClient.java
private static void makeRequest(String url, String method, JSONObject jsonBody, ResponseHandler responseHandler) { HttpURLConnection con = null; int httpResponse = -1; String json = null;// www. j a va 2 s . co m try { con = (HttpURLConnection) new URL(BASE_URL + url).openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); if (jsonBody != null) con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod(method); if (jsonBody != null) { String strJsonBody = jsonBody.toString(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); } httpResponse = con.getResponseCode(); InputStream inputStream; Scanner scanner; if (httpResponse == HttpURLConnection.HTTP_OK) { inputStream = con.getInputStream(); scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json); if (responseHandler != null) responseHandler.onSuccess(json); } else { inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); if (inputStream != null) { scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json); } else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " HTTP Code: " + httpResponse + " No response body!"); if (responseHandler != null) responseHandler.onFailure(httpResponse, json, null); } } catch (Throwable t) { if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException) OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Could not send last request, device is offline. Throwable: " + t.getClass().getName()); else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t); if (responseHandler != null) responseHandler.onFailure(httpResponse, null, t); } finally { if (con != null) con.disconnect(); } }