List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:Main.java
public static String doGet(String urlStr) { URL url = null;/* www .ja v a 2 s. com*/ HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:Main.java
/** * On some devices we have to hack://w w w . jav a 2 s . co m * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:Main.java
public static byte[] doGet(String urlStr) { URL url = null;// www . ja v a 2s . c o m HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toByteArray(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;/*from ww w . j a v a 2 s . c o m*/ try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != HttpStatus.SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:com.example.scandevice.MainActivity.java
public static String excutePost(String targetURL, String urlParameters) { URL url;/*from w w w . ja v a2 s. co m*/ HttpURLConnection connection = null; try { //Create connection url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); } catch (Exception e) { e.printStackTrace(); return "Don't post data"; } finally { if (connection != null) { connection.disconnect(); } } return "Data Sent"; }
From source file:com.google.android.gcm.demo.app.ServerUtilities.java
/** * Issue a POST request to the server.//from www . j a v a2 s.c o m * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } JSONObject jsonObj = new JSONObject(params); String body = jsonObj.toString(); Log.v(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", "application/json"); // 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.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;/* www. ja va 2s.c o m*/ try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:com.bloomreach.bstore.highavailability.utils.SolrInteractionUtils.java
/** * Execute a Http Command with a given read Timeout * * @param timeout/*from ww w. j a v a2 s.c om*/ * @param command * @return {@link java.io.InputStream} of the obtained response * @throws IOException */ public static InputStream executeSolrCommandAndGetInputStreamWithTimeout(int timeout, String command) throws IOException { //logger.info("Command to Execute: " + command); URL obj = new URL(command); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(timeout); //set timeout to 30 seconds con.setReadTimeout(timeout); //set timeout to 30 seconds return con.getInputStream(); }
From source file:com.intuit.tank.harness.AmazonUtil.java
/** * @param string/*w w w .j a v a 2 s. c o m*/ * @return * @throws IOException */ private static InputStream getInputStream(String url) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(3000); return con.getInputStream(); }
From source file:com.screenslicer.core.util.Email.java
public static void sendResults(EmailExport export) { if (WebApp.DEV) { return;//from www . j av a 2 s.co m } Map<String, Object> params = new HashMap<String, Object>(); params.put("key", Config.instance.mandrillKey()); List<Map<String, String>> to = new ArrayList<Map<String, String>>(); for (int i = 0; i < export.recipients.length; i++) { to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i], export.recipients[i].split("@")[0], "to")); } List<Map<String, String>> attachments = new ArrayList<Map<String, String>>(); for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) { attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()), entry.getKey(), Base64.encodeBase64String(entry.getValue()))); } params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers", "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.", "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title, Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments)); params.put("async", true); HttpURLConnection conn = null; String resp = null; Log.info("Sending email: " + export.title, false); try { conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json") .openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0"); String data = CommonUtil.gson.toJson(params, CommonUtil.objectType); byte[] bytes = data.getBytes("utf-8"); conn.setRequestProperty("Content-Length", "" + bytes.length); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); resp = IOUtils.toString(conn.getInputStream(), "utf-8"); if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) { Log.warn("Invalid/rejected email addreses"); } } catch (Exception e) { Log.exception(e); } }