List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java
/** * Helper function gets the rows from the foreign CouchDB server and returns * them as a JSONArray./* w w w . j a v a 2 s . c om*/ */ private static InputStreamReader getViewStream(String user, String pw, String url, String view, String limit, boolean reduce, String groupLevel, boolean hasReducer) throws SQLException { String full_url = ""; try { // TODO: stringbuffer this for efficiency full_url = makeUrl(url, view); String sep = (view.indexOf("?") == -1) ? "?" : "&"; if (limit != null && limit.length() > 0) { full_url += sep + "limit=" + limit; sep = "&"; } // These options only apply if a reducer function is present. if (hasReducer) { if (!reduce) { full_url += sep + "reduce=false"; if (sep.equals("?")) sep = "&"; } if (groupLevel.toUpperCase().equals("EXACT")) full_url += sep + "group=true"; else if (groupLevel.toUpperCase().equals("NONE")) full_url += sep + "group=false"; else full_url += sep + "group_level=" + groupLevel; } logger.log(Level.FINE, "Attempting CouchDB request with URL: " + full_url); URL u = new URL(full_url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); if (user != null && user.length() > 0) { uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw)); } uc.connect(); return new InputStreamReader(uc.getInputStream()); } catch (MalformedURLException e) { throw new SQLException("Bad URL: " + full_url); } catch (IOException e) { if (hasReducer) { // try again but without the reduce args.. try { return getViewStream(user, pw, url, view, limit, reduce, groupLevel, false); } catch (SQLException e2) { // No good. } } throw new SQLException("Could not read data from URL: " + full_url); } }
From source file:com.tohours.imo.util.TohoursUtils.java
/** * //from w w w. ja va 2s . c o m * @param path * @param charsetName * @param param * @return * @throws IOException */ public static String httpPost(String path, String param, String charsetName) throws IOException { String rv = null; URL url = null; HttpURLConnection conn = null; InputStream input = null; try { url = new URL(path); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "plain/text"); conn.setRequestProperty("User-Agent", "Tohours Shake Project"); OutputStream os = conn.getOutputStream(); os.write(param.getBytes(charsetName)); os.flush(); os.close(); input = conn.getInputStream(); rv = TohoursUtils.inputStream2String(input, charsetName); } finally { if (input != null) { input.close(); } } return rv; }
From source file:com.hichengdai.qlqq.front.util.HttpKit.java
/** * /* www .j av a2 s. com*/ * * @param url * @param params * @param file * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ public static String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ? StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ?? StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream fs = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = fs.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // fs.close(); out.write(end_data); out.flush(); out.close(); // BufferedReader???URL? InputStream in = conn.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (conn != null) { // conn.disconnect(); } return bufferRes.toString(); }
From source file:net.mceoin.cominghome.api.NestUtil.java
private static String getNestAwayStatusCall(String access_token) { String away_status = ""; String urlString = "https://developer-api.nest.com/structures?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try {//from w w w.java2 s .c o m URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(15000); // urlConnection.setChunkedStreamingMode(0); // urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // urlConnection.setChunkedStreamingMode(0); // System.out.println("Redirect to URL : " + newUrl); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; InputStream response; response = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); JSONObject structure = object.getJSONObject(key); if (structure.has("away")) { away_status = structure.getString("away"); } else { log.info("missing away"); } } } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) away_status = "Error: " + errorResult; return away_status; }
From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java
/** * Creates a CouchDB view// w w w. j a v a 2 s. com */ public static void makeView(String user, String pw, String url, String viewDef) throws SQLException { try { URL u = new URL(url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); uc.setDoOutput(true); if (user != null && user.length() > 0) { uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw)); } uc.setRequestProperty("Content-Type", "application/json"); uc.setRequestMethod("PUT"); OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream()); wr.write(viewDef); wr.close(); String s = readStringFromConnection(uc); } catch (MalformedURLException e) { throw new SQLException("Bad URL."); } catch (IOException e) { throw new SQLException(e.getMessage()); } }
From source file:fr.zcraft.zbanque.network.PacketSender.java
private static void authenticateRequest(HttpURLConnection connection) { String user = Config.WEBSERVICE.USERNAME.get(); String pass = Config.WEBSERVICE.PASSWORD.get(); if (user == null || user.isEmpty()) return;//w w w .j ava 2 s. c o m if (pass == null) pass = ""; String authToken = Base64.encodeBase64URLSafeString((user + ":" + pass).getBytes()); connection.setRequestProperty("Authorization", "Basic " + authToken); }
From source file:com.avinashbehera.sabera.network.HttpClient.java
public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) { URL sendUrl;//from w w w. j a v a 2 s .c o m try { sendUrl = new URL(url); } catch (MalformedURLException e) { Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL"); return null; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) sendUrl.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(1024); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + ""); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); //writer.write(getPostDataStringfromJsonObject(jsonObjSend)); Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString()); //writer.write(jsonObjSend.toString()); writer.write(String.valueOf(jsonObjSend)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); Log.d(TAG, "responseCode = " + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { Log.d(TAG, "responseCode = HTTP OK"); InputStream instream = conn.getInputStream(); String resultString = convertStreamToString(instream); instream.close(); Log.d(TAG, "resultString = " + resultString); //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONParser parser = new JSONParser(); JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; }
From source file:brainleg.app.util.AppWeb.java
/** * Copied from ITNProxy//from w ww . j av a2 s . co m */ private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException { HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url); connection.setReadTimeout(60 * 1000); connection.setConnectTimeout(10 * 1000); connection.setRequestMethod(HTTP_POST); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING)); connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length)); OutputStream out = new BufferedOutputStream(connection.getOutputStream()); try { out.write(bytes); out.flush(); } finally { out.close(); } return connection; }
From source file:loadTest.loadTestLib.LUtil.java
public static boolean startDockerBuild() throws IOException, InterruptedException { if (useDocker) { if (runInDockerCluster) { HashMap<String, Integer> dockerNodes = getDockerNodes(); String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString() .substring(5);//from w ww . ja v a 2s . com ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size()); dockerError = false; doneDockers = 0; for (Entry<String, Integer> entry : dockerNodes.entrySet()) { exec.submit(new Runnable() { @Override public void run() { try { String url = entry.getKey() + "/images/vauvenal5/loadtest"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("DELETE"); con.setRequestProperty("force", "true"); int responseCode = con.getResponseCode(); con.disconnect(); url = entry.getKey() + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile"; obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/tar"); con.setDoOutput(true); File file = new File(dockerTar); FileInputStream fileStr = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; fileStr.read(b); con.getOutputStream().write(b); con.getOutputStream().flush(); con.getOutputStream().close(); responseCode = con.getResponseCode(); if (responseCode != 200) { dockerError = true; } String msg = ""; do { Thread.sleep(5000); msg = ""; url = entry.getKey() + "/images/json"; obj = new URL(url); HttpURLConnection con2 = (HttpURLConnection) obj.openConnection(); con2.setRequestMethod("GET"); responseCode = con2.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(con2.getInputStream())); String line = null; while ((line = in.readLine()) != null) { msg += line; } con2.disconnect(); } while (!msg.contains("vauvenal5/loadtest")); con.disconnect(); doneDockers++; } catch (MalformedURLException ex) { dockerError = true; } catch (FileNotFoundException ex) { dockerError = true; } catch (IOException ex) { dockerError = true; } catch (InterruptedException ex) { dockerError = true; } } }); } while (doneDockers < dockerNodes.size()) { Thread.sleep(5000); } return !dockerError; } //get the path and substring the 'file:' from the URI String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5); ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest"); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process docker = processBuilder.start(); docker.waitFor(); processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process proc = processBuilder.start(); return proc.waitFor() == 0; } return true; }
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;/*from w w w .j ava 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(); } }