List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.ble.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * //from w w w. ja v a2 s .c o m * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); //url+="&fields=email"; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:fr.zcraft.zbanque.network.PacketSender.java
private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data) throws Throwable { // *** REQUEST *** final URL urlObj = new URL(url); final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod(method.name()); connection.setRequestProperty("User-Agent", USER_AGENT); authenticateRequest(connection);// ww w. j av a2 s .co m connection.setDoOutput(true); try { try { connection.connect(); } catch (IOException ignored) { } if (method == PacketPlayOut.PacketType.POST) { DataOutputStream out = null; try { out = new DataOutputStream(connection.getOutputStream()); if (data != null) out.writeBytes(data); out.flush(); } finally { if (out != null) out.close(); } } // *** RESPONSE *** int responseCode; boolean failed = false; try { responseCode = connection.getResponseCode(); } catch (IOException e) { // HttpUrlConnection will throw an IOException if any 4XX // response is sent. If we request the status again, this // time the internal status will be properly set, and we'll be // able to retrieve it. // Thanks to Iigo. responseCode = connection.getResponseCode(); failed = true; } BufferedReader in = null; String body = ""; try { InputStream stream; try { stream = connection.getInputStream(); } catch (IOException e) { // Same as before stream = connection.getErrorStream(); failed = true; } in = new BufferedReader(new InputStreamReader(stream)); StringBuilder responseBuilder = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { responseBuilder.append(inputLine); } body = responseBuilder.toString(); } finally { if (in != null) in.close(); } HTTPResponse response = new HTTPResponse(); response.setResponseCode(responseCode, failed); response.setResponseBody(body); int i = 0; String headerName, headerContent; while ((headerName = connection.getHeaderFieldKey(i)) != null) { headerContent = connection.getHeaderField(i); response.addHeader(headerName, headerContent); } // *** REDIRECTION *** switch (responseCode) { case 301: case 302: case 307: case 308: if (response.getHeaders().containsKey("Location")) { response = makeRequest(response.getHeaders().get("Location"), method, data); } } // *** END *** return response; } finally { connection.disconnect(); } }
From source file:fr.ms.tomcat.manager.TomcatManagerUrl.java
public static String appelUrl(final URL url, final String username, final String password, final String charset) { try {/*w w w. j av a2 s.c o m*/ final URLConnection urlTomcatConnection = url.openConnection(); final HttpURLConnection connection = (HttpURLConnection) urlTomcatConnection; LOG.debug("url : " + url); connection.setAllowUserInteraction(false); connection.setDoInput(true); connection.setUseCaches(false); connection.setDoOutput(false); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", toAuthorization(username, password)); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new TomcatManagerException("Reponse http : " + connection.getResponseMessage() + " - Les droits \"manager\" ne sont pas appliques - utilisateur : \"" + username + "\" password : \"" + password + "\""); } throw new TomcatManagerException("HttpURLConnection.HTTP_UNAUTHORIZED"); } final String response = toString(connection.getInputStream(), charset); LOG.debug("reponse : " + response); return response; } catch (final Exception e) { throw new TomcatManagerException("L'url du manager tomcat est peut etre incorrecte : \"" + url + "\"", e); } }
From source file:org.pixmob.fm2.util.HttpUtils.java
/** * Prepare a <code>POST</code> Http request. *//*from w w w .j a va2 s. c o m*/ public static HttpURLConnection newPostRequest(Context context, String uri, Set<String> cookies, Map<String, String> params, String charset) throws IOException { final StringBuilder query = new StringBuilder(); if (params != null) { for (final Map.Entry<String, String> e : params.entrySet()) { if (query.length() != 0) { query.append("&"); } query.append(e.getKey()).append("=").append(URLEncoder.encode(e.getValue())); } } final byte[] payload = query.toString().getBytes(charset); final HttpURLConnection conn = newRequest(context, uri, cookies); conn.setDoOutput(true); conn.setFixedLengthStreamingMode(payload.length); conn.setRequestProperty("Accept-Charset", charset); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); conn.setRequestProperty("Referer", uri); final OutputStream queryOutput = conn.getOutputStream(); try { queryOutput.write(payload); } finally { IOUtils.close(queryOutput); } return conn; }
From source file:com.sample.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * // ww w .jav a2 s . c o m * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); //url+="&fields=email"; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setConnectTimeout(45000); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.magnet.plugin.common.helpers.URLHelper.java
public static String checkURLConnection(String urlS, String username, String password) { String status = "Error connection to server!"; FormattedLogger logger = new FormattedLogger(URLHelper.class); logger.append("checkURLConnection:" + urlS); try {// w ww . j av a2 s . co m URL url = new URL(urlS); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (username != null && username.trim().length() > 0 && password != null && password.trim().length() > 0) { final String authString = username + ":" + password; conn.setRequestProperty("Authorization", "Basic " + Base64.encode(authString.getBytes())); } conn.setRequestMethod("GET"); conn.setDoInput(true); status = "" + conn.getResponseCode(); logger.append("Response code:" + status); logger.showInfoLog(); } catch (Exception e) { logger.append(">>>" + e.getClass().getName() + " message: " + e.getMessage()); logger.showErrorLog(); } return status; }
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;/*from ww w. j ava 2 s.c o m*/ 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:com.example.makerecg.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password./*from w ww.j av a 2 s .com*/ * 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.example.makerecg.NetworkUtilities.java
/** * Perform 2-way sync with the server-side ADSampleFrames. We send a request that * includes all the locally-dirty contacts so that the server can process * those changes, and we receive (and return) a list of contacts that were * updated on the server-side that need to be updated locally. * * @param account The account being synced * @param authtoken The authtoken stored in the AccountManager for this * account//from w w w .j a v a 2 s . co m * @param serverSyncState A token returned from the server on the last sync * @param dirtyFrames A list of the frames to send to the server * @return A list of frames that we need to update locally */ public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState, List<ADSampleFrame> dirtyFrames) throws JSONException, ParseException, IOException, AuthenticationException { List<JSONObject> jsonFrames = new ArrayList<JSONObject>(); for (ADSampleFrame frame : dirtyFrames) { jsonFrames.add(frame.toJSONObject()); } JSONArray buffer = new JSONArray(jsonFrames); JSONObject top = new JSONObject(); top.put("data", buffer); // Create an array that will hold the server-side ADSampleFrame // that have been changed (returned by the server). final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>(); // Send the updated frames data to the server //Log.i(TAG, "Syncing to: " + SYNC_URI); URL urlToRequest = new URL(SYNC_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + authtoken); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(top.toString(1)); writer.flush(); writer.close(); os.close(); //Log.i(TAG, "body="+top.toString(1)); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { // Our request to the server was successful - so we assume // that they accepted all the changes we sent up, and // that the response includes the contacts that we need // to update on our side... // TODO: Only uploading data for now ... String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); //Log.i(TAG, "response="+response); /* final JSONArray serverContacts = new JSONArray(response); Log.d(TAG, response); for (int i = 0; i < serverContacts.length(); i++) { ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i)); if (rawContact != null) { serverDirtyList.add(rawContact); } } */ } else { if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in while uploading data"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in sending sample frames: " + responseCode); throw new IOException(); } } return null; }
From source file:com.denimgroup.threadfix.service.defects.RestUtils.java
public static void setupAuthorization(HttpURLConnection connection, String username, String password) { String login = username + ":" + password; String encodedLogin = new String(Base64.encodeBase64(login.getBytes())); //String encodedLogin = Base64.encodeBase64String(login.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedLogin); }