List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.cloudbees.workflow.Util.java
public static int postToJenkins(Jenkins jenkins, String url, String content, String contentType) throws IOException { String jenkinsUrl = jenkins.getRootUrl(); URL urlObj = new URL(jenkinsUrl + url.replace("/jenkins/job/", "job/")); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); try {//w ww .jav a 2s . com conn.setRequestMethod("POST"); // Set the crumb header, otherwise the POST may be rejected. NameValuePair crumbHeader = getCrumbHeaderNVP(jenkins); conn.setRequestProperty(crumbHeader.getName(), crumbHeader.getValue()); if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } if (content != null) { byte[] bytes = content.getBytes(Charset.forName("UTF-8")); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); final OutputStream os = conn.getOutputStream(); try { os.write(bytes); os.flush(); } finally { os.close(); } } return conn.getResponseCode(); } finally { conn.disconnect(); } }
From source file:com.chiorichan.util.WebUtils.java
public static boolean sendTracking(String category, String action, String label) { String url = "http://www.google-analytics.com/collect"; try {/* w w w. j a va2s . c o m*/ URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category + "&ea=" + action + "&el=" + label; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Loader.getLogger().fine("Analytics Response [" + category + "]: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return true; } catch (IOException e) { return false; } }
From source file:com.cyphermessenger.client.SyncRequest.java
public static HttpURLConnection doRequest(String endpoint, CypherSession session, String[] keys, String[] values) throws IOException { HttpURLConnection connection = (java.net.HttpURLConnection) new URL(DOMAIN + endpoint).openConnection(); connection.setDoOutput(true);//from w w w . j a v a 2s .c o m connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.connect(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); if (session != null) { writer.write("userID="); writer.write(session.getUser().getUserID() + "&sessionID="); writer.write(session.getSessionID()); } if (keys != null && keys.length > 0) { if (session != null) { writer.write('&'); } // write first row writer.write(keys[0]); writer.write('='); writer.write(URLEncoder.encode(values[0], "UTF-8")); for (int i = 1; i < keys.length; i++) { writer.write('&'); writer.write(keys[i]); writer.write('='); writer.write(URLEncoder.encode(values[i], "UTF-8")); } } writer.close(); return connection; }
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Upload ontology content on specified dataset. Graph used is the default * one except if specified/*from w w w .j av a 2 s .c o m*/ * * @param ontology * @param datasetName * @param graphName * @throws IOException * @throws HttpException */ public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName) throws IOException, HttpException { graphName = Strings.emptyToNull(graphName); logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName)); boolean createGraph = (graphName != null) ? true : false; String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8"); String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null; URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : "")); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); String boundary = "------------------" + System.currentTimeMillis() + Long.toString(Math.round(Math.random() * 1000)); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConnection.setRequestProperty("Connection", "keep-alive"); httpConnection.setRequestProperty("Cache-Control", "no-cache"); // set content httpConnection.setDoOutput(true); final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream()); out.write(BOUNDARY_DECORATOR + boundary + EOL); out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL); out.write("Content-Type: application/octet-stream" + EOL + EOL); out.write(CharStreams.toString(new InputStreamReader(ontology))); out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL); out.close(); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_CREATED: checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } }
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 w w w .jav a 2s.c o m * * @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:com.example.makerecg.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password.//from w w w .j a v a 2 s . c o m * 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:BihuHttpUtil.java
/** * ??HTTPJSON?/*from w w w .j a va 2 s . c o m*/ * @param url * @param jsonStr */ public static String sendPostForJson(String url, String jsonStr) { StringBuffer sb = new StringBuffer(""); try { // URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); connection.connect(); //POST DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(jsonStr.getBytes("UTF-8"));//??? out.flush(); out.close(); //?? BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } reader.close(); // connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
From source file:com.androidex.volley.toolbox.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { ProgressListener progressListener = null; if (request instanceof ProgressListener) { progressListener = (ProgressListener) request; }/*from w w w .j a v a 2 s . c o m*/ connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (progressListener != null) { int transferredBytes = 0; int totalSize = body.length; int offset = 0; int chunkSize = Math.min(2048, Math.max(totalSize - offset, 0)); while (chunkSize > 0 && offset + chunkSize <= totalSize) { out.write(body, offset, chunkSize); transferredBytes += chunkSize; progressListener.onProgress(transferredBytes, totalSize); offset += chunkSize; chunkSize = Math.min(chunkSize, Math.max(totalSize - offset, 0)); } } else { out.write(body); } out.close(); } }
From source file:com.pubkit.network.PubKitNetwork.java
public static JSONObject sendPost(String apiKey, JSONObject jsonObject) { URL url;//w w w. j a va 2 s .c o m HttpURLConnection connection = null; try { //Create connection url = new URL(PUBKIT_API_URL); String encodedData = jsonObject.toString(); byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length)); connection.setRequestProperty("api_key", apiKey); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(encodedData);//set data wr.flush(); //Get Response InputStream inputStream = connection.getErrorStream(); //first check for error. if (inputStream == null) { inputStream = connection.getInputStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } wr.close(); rd.close(); String responseString = response.toString(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return new JSONObject("{'error':'" + responseString + "'}"); } else { try { return new JSONObject(responseString); } catch (JSONException e) { Log.e("PUBKIT", "Error parsing data", e); } } } catch (Exception e) { Log.e("PUBKIT", "Network exception:", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:Main.java
public static String request(String url, Map<String, String> cookies, Map<String, String> parameters) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"); if (cookies != null && !cookies.isEmpty()) { StringBuilder cookieHeader = new StringBuilder(); for (String cookie : cookies.values()) { if (cookieHeader.length() > 0) { cookieHeader.append(";"); }/*from www . j a v a2 s. c om*/ cookieHeader.append(cookie); } connection.setRequestProperty("Cookie", cookieHeader.toString()); } connection.setDoInput(true); if (parameters != null && !parameters.isEmpty()) { connection.setDoOutput(true); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(parametersToWWWFormURLEncoded(parameters)); osw.flush(); osw.close(); } if (cookies != null) { for (Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) { if (headerEntry != null && headerEntry.getKey() != null && headerEntry.getKey().equalsIgnoreCase("Set-Cookie")) { for (String header : headerEntry.getValue()) { for (HttpCookie httpCookie : HttpCookie.parse(header)) { cookies.put(httpCookie.getName(), httpCookie.toString()); } } } } } Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringWriter w = new StringWriter(); char[] buffer = new char[1024]; int n = 0; while ((n = r.read(buffer)) != -1) { w.write(buffer, 0, n); } r.close(); return w.toString(); }