List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:core.RESTCalls.RESTPost.java
public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true);//from ww w . j a va2 s.c o m conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream out = conn.getOutputStream(); Writer writer = new OutputStreamWriter(out, "UTF-8"); for (int i = 0; i < paramName.length; i++) { writer.write(paramName[i]); writer.write("="); writer.write(URLEncoder.encode(paramVal[i], "UTF-8")); writer.write("&"); } writer.close(); out.close(); if (conn.getResponseCode() != 200) throw new IOException(conn.getResponseMessage()); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) sb.append(line + "\n"); rd.close(); conn.disconnect(); return sb.toString(); }
From source file:cloudlens.parser.FileReader.java
public static InputStream fetchFile(String urlString) { try {/*from w ww . j ava 2 s .c o m*/ InputStream inputStream; URL url; if (urlString.startsWith("local:")) { final String path = urlString.replaceFirst("local:", ""); inputStream = Files.newInputStream(Paths.get(path)); } else if (urlString.startsWith("file:")) { url = new URL(urlString); inputStream = Files.newInputStream(Paths.get(url.toURI())); } else if (urlString.startsWith("http:") || urlString.startsWith("https:")) { url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString); if (matcher.find()) { final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes()); conn.setRequestProperty("Authorization", "Basic " + encoding); } conn.setRequestMethod("GET"); inputStream = conn.getInputStream(); } else { throw new CLException("supported protocols are: http, https, file, and local."); } return inputStream; } catch (IOException | URISyntaxException e) { throw new CLException(e.getMessage()); } }
From source file:br.gov.jfrj.siga.base.ConexaoHTTP.java
public static String get(String URL, HashMap<String, String> header, Integer timeout, String payload) throws AplicacaoException { try {//from w ww. j a va 2 s . c o m HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection(); if (timeout != null) { conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); } //conn.setInstanceFollowRedirects(true); if (header != null) { for (String s : header.keySet()) { conn.setRequestProperty(s, header.get(s)); } } System.setProperty("http.keepAlive", "false"); if (payload != null) { byte ab[] = payload.getBytes("UTF-8"); conn.setRequestMethod("POST"); // Send post request conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(ab); os.flush(); os.close(); } //StringWriter writer = new StringWriter(); //IOUtils.copy(conn.getInputStream(), writer, "UTF-8"); //return writer.toString(); return IOUtils.toString(conn.getInputStream(), "UTF-8"); } catch (IOException ioe) { throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe); } }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Checks if is reachable.//from w w w . ja va2 s . co m * * @param uri the uri * @param headers the headers * @return true, if is reachable */ public static boolean isReachable(String uri, HashMap<String, String> headers) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection(); myURLConnection.setRequestMethod("HEAD"); for (String key : headers.keySet()) { myURLConnection.setRequestProperty("Authorization", headers.get(key)); } LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString()); return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:chen.android.toolkit.network.HttpConnection.java
/** * </br><b>title : </b> ????POST?? * </br><b>description :</b>????POST?? * </br><b>time :</b> 2012-7-8 ?4:34:08 * @param method ??//w ww . java 2s. co m * @param url POSTURL * @param datas ???? * @return ??? * @throws IOException */ private static InputStream connect(String method, URL url, byte[]... datas) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setConnectTimeout(6 * 1000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); OutputStream outputStream = conn.getOutputStream(); for (byte[] data : datas) { outputStream.write(data); } outputStream.close(); return conn.getInputStream(); }
From source file:com.android.volley.toolbox.http.HurlStack.java
/** * Add headers and user agent to an {@code } * * @param connection The {@linkplain HttpURLConnection} to add request headers to * @param userAgent The User Agent to identify on server * @param additionalHeaders The headers to add to the request */// w w w . j a v a 2 s.c o m private static void addHeadersToConnection(HttpURLConnection connection, String userAgent, Map<String, String> additionalHeaders) { connection.setRequestProperty(HEADER_USER_AGENT, userAgent); for (String headerName : additionalHeaders.keySet()) { connection.addRequestProperty(headerName, additionalHeaders.get(headerName)); } }
From source file:com.grosscommerce.ICEcat.utilities.Downloader.java
private static HttpURLConnection prepareConnection(String urlFrom, String login, String pwd) throws ProtocolException, IOException, MalformedURLException { URL url = new URL(urlFrom); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); // set up url connection to get retrieve information back uc.setRequestMethod("GET"); uc.setDoInput(true);/* w ww .jav a2 s. c o m*/ String val = (new StringBuffer(login).append(":").append(pwd)).toString(); byte[] base = val.getBytes(); String authorizationString = "Basic " + Base64.encodeBase64String(base); uc.setRequestProperty("Authorization", authorizationString); uc.setRequestProperty("Accept-Encoding", "gzip, xml"); return uc; }
From source file:Main.java
/** * Issue a POST request to the server.//from ww w.ja va2s . c o m * * @param endpoint POST address. * @param params request parameters. * @return response * @throws IOException propagated from POST. */ private static String executePost(String endpoint, Map<String, String> params) throws IOException { URL url; StringBuffer response = new StringBuffer(); try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); //Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // 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); } else { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } } finally { if (conn != null) { conn.disconnect(); } } return response.toString(); }
From source file:com.ble.facebook.Util.java
public static String posttowall(String url, String method, Bundle params, String Accesstoken) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os;//from ww w.j av a 2 s .com if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); 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.putByteArray("method", method.getBytes()); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(Accesstoken); params.putByteArray("access_token", decoded_token.getBytes()); } 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()); Log.d("OutputStreamedData", ("--" + strBoundary + endLine) + (encodePostBody(params, strBoundary)) + (endLine + "--" + strBoundary + endLine)); 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.wareninja.android.opensource.oauth2login.common.Utils.java
/** * Connect to an HTTP URL and return the response as a string. * /*from w w w. jav a 2 s .c om*/ * 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); } if (AppContext.DEBUG) Log.d("Facebook-Util", method + " URL: " + url); 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)); } */ // YG: added this to avoid fups byte[] byteArr = null; try { byteArr = (byte[]) params.get(key); } catch (Exception ex1) { } if (byteArr != null) dataparams.putByteArray(key, byteArr); } // 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()); } if (AppContext.DEBUG) Log.d("Facebook-Util", method + " response: " + response); return response; }