List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean putObjectAcl(String bucketName, String objectKey, ACL acl, String awsAccessId, String awsSecretKey) throws IOException { final String date = getDate(); final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl"); final String payload = String.format(PUT_PAYLOAD_ACL, date, acl.toString(), bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); HttpURLConnection conn = null; try {/* w w w . j a va 2 s . com*/ conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Date", date); conn.setRequestProperty("x-amz-acl", acl.toString()); conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error setting ACL for: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.android.dialer.omni.PlaceUtil.java
/** * Executes a post request and return a JSON object * @param url The API URL/*from w w w. jav a2 s.co m*/ * @param data The data to post in POST field * @return the JSON object * @throws IOException * @throws JSONException */ public static JSONObject postJsonRequest(String url, String postData) throws IOException, JSONException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); if (DEBUG) Log.d(TAG, "Posting: " + postData + " to " + url); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return json; }
From source file:Main.java
public static String simplePost(String url, Bundle params, String method) throws MalformedURLException, IOException { OutputStream os;//from w w w . java 2 s . co m System.setProperty("http.keepAlive", "false"); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent"); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.setDoInput(true); //conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(encodePostParams(params).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.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 .java2 s .c om*/ * @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: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. ja v a2s . 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:Main.java
public static String openUrl(String url, String method, Bundle params) { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); }// w w w .j a v a 2s.co m String response = ""; try { Log.d(LOG_TAG, method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK"); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } response = read(conn.getInputStream()); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); throw new RuntimeException(e.getMessage(), e); } return response; }
From source file:org.pixmob.fm2.util.HttpUtils.java
/** * Prepare a <code>POST</code> Http request. *//*from ww w. j ava 2 s. co 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:ly.stealth.punxsutawney.Marathon.java
private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException { URL url = new URL(Marathon.url + uri); HttpURLConnection c = (HttpURLConnection) url.openConnection(); try {//from w w w . j ava 2s. co m c.setRequestMethod(method); if (method.equalsIgnoreCase("POST")) { byte[] body = json.toString().getBytes("utf-8"); c.setDoOutput(true); c.setRequestProperty("Content-Type", "application/json"); c.setRequestProperty("Content-Length", "" + body.length); c.getOutputStream().write(body); } return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8")); } catch (IOException e) { if (c.getResponseCode() == 404 && method.equals("GET")) return null; ByteArrayOutputStream response = new ByteArrayOutputStream(); InputStream err = c.getErrorStream(); if (err == null) throw e; Util.copyAndClose(err, response); IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8")); ne.setStackTrace(e.getStackTrace()); throw ne; } finally { c.disconnect(); } }
From source file:com.playbasis.android.playbasissdk.http.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 ww w .j a v a 2 s. co m*/ } }
From source file:io.github.retz.web.JobRequestRouter.java
private static String fetchHTTP(String addr, int retry) throws MalformedURLException, IOException { LOG.debug("Fetching {}", addr); HttpURLConnection conn = null; try {//from w ww. j ava 2s . co m conn = (HttpURLConnection) new URL(addr).openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); LOG.debug(conn.getResponseMessage()); } catch (MalformedURLException e) { LOG.error(e.toString()); throw e; } catch (IOException e) { LOG.error(e.toString()); throw e; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), UTF_8))) { StringBuilder builder = new StringBuilder(); String line; do { line = reader.readLine(); builder.append(line); } while (line != null); LOG.debug("Fetched {} bytes from {}", builder.toString().length(), addr); return builder.toString(); } catch (FileNotFoundException e) { throw e; } catch (IOException e) { // Somehow this happens even HTTP was correct LOG.debug("Cannot fetch file {}: {}", addr, e.toString()); // Just retry until your stack get stuck; thanks to SO:33340848 // and to that crappy HttpURLConnection if (retry < 0) { LOG.error("Retry failed. Last error was: {}", e.toString()); throw e; } return fetchHTTP(addr, retry - 1); } finally { conn.disconnect(); } }