List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.none.tom.simplerssreader.net.FeedDownloader.java
@SuppressWarnings("ConstantConditions") public static InputStream getInputStream(final Context context, final String feedUrl) { final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class); final NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK); LogUtils.logError("No network connection"); return null; }//from w ww . j av a 2 s .c o m URL url; try { url = new URL(feedUrl); } catch (final MalformedURLException e) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e); return null; } final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context); final boolean useHttpTorProxy = networkPrefs[0]; final boolean httpsOnly = networkPrefs[1]; final boolean followRedir = networkPrefs[2]; for (int nrRedirects = 0;; nrRedirects++) { if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS); LogUtils.logError("Too many redirects"); return null; } HttpURLConnection conn = null; try { if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY); LogUtils.logError("Attempting insecure connection"); return null; } if (useHttpTorProxy) { conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT))); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.connect(); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: return getInputStream(conn.getInputStream()); case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: if (followRedir) { final String location = conn.getHeaderField("Location"); url = new URL(url, location); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) { SharedPrefUtils.updateSubscriptionUrl(context, url.toString()); } continue; } ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED); LogUtils.logError("Couldn't follow redirect"); return null; default: if (responseCode < 0) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE); LogUtils.logError("No valid HTTP response"); return null; } else if (responseCode >= 400 && responseCode <= 500) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT); } else if (responseCode >= 500 && responseCode <= 600) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED); } LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage()); return null; } } catch (final IOException e) { if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable")) || e instanceof SocketTimeoutException || e instanceof UnknownHostException) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e); } return null; } finally { if (conn != null) { conn.disconnect(); } } } }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException { c.setInstanceFollowRedirects(false); c.setDoOutput(true);//from www . j av a2 s .com c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", form.contentType()); c.setRequestProperty("Content-Length", form.length()); c.connect(); try (OutputStream os = c.getOutputStream()) { os.write(form.content()); } return fromStatusCode(c.getResponseCode()); }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends an HTTP GET request to a url/*from ww w . j a va2 s . c o m*/ * * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search") * @param file the output file. If it is a folder, it tries to get the file name from the header. * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). * Note: This method will add the question mark (?) to the request - * DO NOT add it yourself * @param user user. * @param password password. * @return the file written. * @throws Exception if something goes wrong. */ public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user, String password) throws Exception { if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } HttpURLConnection conn = makeNewConnection(urlStr); conn.setRequestMethod("GET"); // conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); if (file.isDirectory()) { // try to get the header String headerField = conn.getHeaderField("Content-Disposition"); String fileName = null; if (headerField != null) { String[] split = headerField.split(";"); for (String string : split) { String pattern = "filename="; if (string.toLowerCase().startsWith(pattern)) { fileName = string.replaceFirst(pattern, ""); break; } } } if (fileName == null) { // give a name fileName = "FILE_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.format(new Date()); } file = new File(file, fileName); } InputStream in = null; FileOutputStream out = null; try { in = conn.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[(int) maxBufferSize]; int bytesRead = in.read(buffer, 0, (int) maxBufferSize); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer, 0, (int) maxBufferSize); } out.flush(); } finally { if (in != null) in.close(); if (out != null) out.close(); if (conn != null) conn.disconnect(); } return file; }
From source file:com.mnt.base.util.HttpUtil.java
public static String processPostRequest2Text(String url, Map<String, Object> parameters, Map<String, String> headerValue) { HttpURLConnection connection = null; try {//from w ww. j a v a 2 s .c om connection = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { log.error("Error while process http get request.", e); } if (connection != null) { try { connection.setRequestMethod("POST"); connection.setDoOutput(true); } catch (ProtocolException e) { log.error("should not happen to get error while set the request method as GET.", e); } if (!CommonUtil.isEmpty(headerValue)) { for (String key : headerValue.keySet()) { connection.setRequestProperty(key, headerValue.get(key)); } } // need to specify the content type for post request connection.setRequestProperty("Content-Type", "application/json"); setTimeout(connection); String resultStr = null; try { connection.connect(); if (parameters != null) { String jsonParams = null; try { jsonParams = JSONTool.convertObjectToJson(parameters); } catch (Exception e) { log.error("error while process parameters to json string.", e); } if (jsonParams != null) { connection.getOutputStream().write(jsonParams.getBytes()); connection.getOutputStream().flush(); } } resultStr = readData(connection.getInputStream()); } catch (IOException e) { log.error("fail to connect to url: " + url, e); } finally { connection.disconnect(); } return resultStr; } return null; }
From source file:com.screenslicer.common.CommonUtil.java
public static String post(String uri, String recipient, String postData) { HttpURLConnection conn = null; try {/*ww w . j a v a 2 s. com*/ postData = Crypto.encode(postData, recipient); conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setConnectTimeout(0); conn.setRequestProperty("Content-Type", "application/json"); byte[] bytes = postData.getBytes("utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); if (conn.getResponseCode() == 205) { return NOT_BUSY; } if (conn.getResponseCode() == 423) { return BUSY; } return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient); } catch (Exception e) { Log.exception(e); } return ""; }
From source file:org.csware.ee.utils.Tools.java
public static String reqByPost(String path, String sessionId) { String info = ""; try {/*from w w w.ja v a 2 s . c o m*/ // URL URL url = new URL(path); // HttpURLConnection HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Cookie", sessionId); InputStream in = urlConn.getInputStream(); try { byte[] buffer = new byte[65536]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int readLength = in.read(buffer); long totalLength = 0; while (readLength >= 0) { bos.write(buffer, 0, readLength); totalLength = totalLength + readLength; readLength = in.read(buffer); } info = bos.toString("UTF-8"); } finally { if (in != null) try { in.close(); } catch (Exception e) { e.printStackTrace(); } } // urlConn.setConnectTimeout(5 * 1000); // urlConn.connect(); } catch (Exception ex) { ex.printStackTrace(); return ""; } return info.replaceAll("\r\n", " "); }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static HttpURLConnection createConnection(String url, String username, String password) throws IOException { boolean useAuth = !password.equals(""); // force SSL if useAuth=true (would send password unencrypted otherwise) boolean useSSL = useAuth || url.startsWith("https"); Log.d("HttpPost", "password: " + password); Log.d("HttpPost", "useSSL: " + useSSL); if (useSSL) { if (!url.startsWith("https")) { // replace http: with https: -- this will obviously screw // up if input is something other than http so don't do that :) url = "https:" + url.substring(5); }//from w w w . j av a2 s .c o m // would rather not do this, need to check if there's still a problem // with our ssl certificates on NASA servers. try { DisableSSLCertificateCheckUtil.disableChecks(); } catch (GeneralSecurityException e) { throw new IOException("HttpPost - disable ssl: " + e); } } HttpURLConnection conn; try { if (useSSL) { conn = (HttpsURLConnection) (new URL(url)).openConnection(); } else { conn = (HttpURLConnection) (new URL(url)).openConnection(); } } catch (IOException e) { throw new IOException("HttpPost - IOException: " + e); } if (useAuth) { // add pre-emptive http basic authentication. using // homebrew version -- early versions of android // authenticator have problems and this is easy. String userpassword = username + ":" + password; String encodedAuthorization = Base64.encode(userpassword.getBytes()); conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization); } conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(true); return conn; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a string via POST to a given url. * * @param context the context to use. * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message. * @return the response.//from w ww . jav a 2 s .c om * @throws Exception if something goes wrong. */ public static String sendPost(Context context, String urlStr, String string, String user, String password, boolean readResponse) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); if (readResponse) { StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } else { return getMessageForCode(context, responseCode, context.getResources().getString(R.string.post_completed_properly)); } } catch (Exception e) { throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.iStudy.Study.Renren.Util.java
private static HttpURLConnection sendFormdata(String reqUrl, Bundle parameters, String fileParamName, String filename, String contentType, byte[] data) { HttpURLConnection urlConn = null; try {/*from www . j a va 2 s. c o m*/ URL url = new URL(reqUrl); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(5000);// ??jdk urlConn.setReadTimeout(5000);// ??jdk 1.5??,? urlConn.setDoOutput(true); urlConn.setRequestProperty("connection", "keep-alive"); String boundary = "-----------------------------114975832116442893661388290519"; // urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; StringBuffer params = new StringBuffer(); if (parameters != null) { for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) { String name = iter.next(); String value = parameters.getString(name); params.append(boundary + "\r\n"); params.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"); // params.append(URLEncoder.encode(value, "UTF-8")); params.append(value); params.append("\r\n"); } } StringBuilder sb = new StringBuilder(); sb.append(boundary); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + filename + "\"\r\n"); sb.append("Content-Type: " + contentType + "\r\n\r\n"); byte[] fileDiv = sb.toString().getBytes(); byte[] endData = ("\r\n" + boundary + "--\r\n").getBytes(); byte[] ps = params.toString().getBytes(); OutputStream os = urlConn.getOutputStream(); os.write(ps); os.write(fileDiv); os.write(data); os.write(endData); os.flush(); os.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return urlConn; }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
/** * Apply normalization rules to the identifier supplied by the End-User * to determine the Resource and Host. Then make an HTTP GET request to * the host's WebFinger endpoint to obtain the location of the requested * service/*from ww w . ja v a 2 s. c o m*/ * return the issuer location ("href") * @param user_input , domain * @return */ public static String webfinger(String userInput, String serverUrl) { // android.os.Debug.waitForDebugger(); String result = ""; // result of the http request (a json object // converted to string) String postUrl = ""; String host = null; String href = null; // URI identifying the type of service whose location is being requested final String rel = "http://openid.net/specs/connect/1.0/issuer"; if (!isEmpty(userInput)) { try { // normalizes this URI's path URI uri = new URI(userInput).normalize(); String[] parts = uri.getRawSchemeSpecificPart().split("@"); if (!isEmpty(serverUrl)) { // use serverUrl if specified if (serverUrl.startsWith("https://")) { host = serverUrl.substring(8); } else if (serverUrl.startsWith("http://")) { host = serverUrl.substring(7); } else { host = serverUrl; } } else if (parts.length > 1) { // the user is using an E-Mail Address Syntax host = parts[parts.length - 1]; } else { // the user is using an other syntax host = uri.getHost(); } // check if host is valid if (host == null) { return null; } if (!host.endsWith("/")) host += "/"; postUrl = "https://" + host + ".well-known/webfinger?resource=" + userInput + "&rel=" + rel; // log the request Logd(TAG, "Web finger request\n GET " + postUrl + "\n HTTP /1.1" + "\n Host: " + host); // Send an HTTP get request with the resource and rel parameters HttpURLConnection huc = getHUC(postUrl); huc.setDoOutput(true); huc.setRequestProperty("Content-Type", "application/jrd+json"); huc.connect(); try { int responseCode = huc.getResponseCode(); Logd(TAG, "webfinger responseCode: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); Logd(TAG, "webfinger result: " + result); // The response is a json object and the issuer location // is returned as the value of the href member // a links array element with the rel member value // http://openid.net/specs/connect/1.0/issuer JSONObject jo = new JSONObject(result); JSONObject links = jo.getJSONArray("links").getJSONObject(0); href = links.getString("href"); Logd(TAG, "webfinger reponse href: " + href); } else { // why the request didn't succeed href = huc.getResponseMessage(); } // close connection huc.disconnect(); } catch (IOException ioe) { Logd(TAG, "webfinger io exception: " + huc.getErrorStream()); ioe.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } else { // the user_input is empty href = "no identifier detected!!\n"; } return href; }