List of usage examples for java.net HttpURLConnection setAllowUserInteraction
public void setAllowUserInteraction(boolean allowuserinteraction)
From source file:org.bibsonomy.util.WebUtils.java
/** * Sends a request to the given URL and checks, if it contains a redirect. * If it does, returns the redirect URL. Otherwise, returns null. * This is done up to {@value #MAX_REDIRECT_COUNT}-times until the final page is reached. * /*from w w w. j a v a2 s . c o m*/ * * * @param url * @return - The redirect URL. */ public static URL getRedirectUrl(final URL url) { try { URL internalUrl = url; URL previousUrl = null; int redirectCtr = 0; while (internalUrl != null && redirectCtr < MAX_REDIRECT_COUNT) { redirectCtr++; final HttpURLConnection urlConn = (HttpURLConnection) internalUrl.openConnection(); urlConn.setAllowUserInteraction(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); /* * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some * pages require it to download content. */ urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE); urlConn.connect(); // get URL to redirected resource previousUrl = internalUrl; try { internalUrl = new URL(urlConn.getHeaderField(LOCATION)); } catch (final MalformedURLException e) { internalUrl = null; } urlConn.disconnect(); } return previousUrl; } catch (final IOException e) { e.printStackTrace(); return null; } }
From source file:org.rapidcontext.app.plugin.http.HttpPostProcedure.java
/** * Creates an HTTP connection for the specified URL and headers. * * @param url the URL to use//from ww w .j av a2 s . co m * @param headers the additional HTTP headers * * @return the HTTP connection created * * @throws ProcedureException if the connection couldn't be created */ private static HttpURLConnection createConnection(URL url, Map headers) throws ProcedureException { HttpURLConnection con; String msg; try { con = (HttpURLConnection) url.openConnection(); } catch (IOException e) { msg = "failed to open URL " + url + ":" + e.getMessage(); throw new ProcedureException(msg); } con.setDoInput(true); con.setAllowUserInteraction(false); con.setUseCaches(false); con.setInstanceFollowRedirects(false); con.setConnectTimeout(10000); con.setReadTimeout(45000); con.setRequestProperty("Cache-Control", "no-cache"); con.setRequestProperty("Accept", "text/*, application/*"); con.setRequestProperty("Accept-Charset", "UTF-8"); con.setRequestProperty("Accept-Encoding", "identity"); // TODO: Extract correct version number from JAR file con.setRequestProperty("User-Agent", "RapidContext/1.0"); Iterator iter = headers.keySet().iterator(); while (iter.hasNext()) { String str = (String) iter.next(); con.setRequestProperty(str, (String) headers.get(str)); } return con; }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {//from w ww .j av a 2 s . co m // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:org.wso2.carbon.esb.passthru.transport.test.ESBJAVA4891ConsumeAndDiscardTest.java
private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws AutomationFrameworkException, IOException { HttpURLConnection urlConnection = null; try {/*from ww w .ja v a2s. c om*/ urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new AutomationFrameworkException( "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); urlConnection.setReadTimeout(10000); for (Map.Entry<String, String> e : headers.entrySet()) { urlConnection.setRequestProperty(e.getKey(), e.getValue()); } OutputStream out = urlConnection.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); writer.close(); } catch (IOException e) { throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e); } StringBuilder sb = new StringBuilder(); BufferedReader rd; try { rd = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap<>(); String key; while (itr.hasNext()) { key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { StringBuilder sb = new StringBuilder(); BufferedReader rd = null; rd = new BufferedReader( new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } return new HttpResponse(sb.toString(), urlConnection.getResponseCode()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:org.wso2.carbon.esb.passthru.transport.test.PartialInputStreamReadError.java
private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws AutomationFrameworkException, IOException { HttpURLConnection urlConnection = null; try {//from w w w. ja v a 2 s .com urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new AutomationFrameworkException( "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); urlConnection.setReadTimeout(10000); for (Map.Entry<String, String> e : headers.entrySet()) { urlConnection.setRequestProperty(e.getKey(), e.getValue()); } OutputStream out = urlConnection.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); writer.close(); } catch (IOException e) { throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e); } StringBuilder sb = new StringBuilder(); BufferedReader rd; try { rd = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Object responseHeaders = new HashMap(); String key; while (itr.hasNext()) { key = itr.next(); if (key != null) { ((Map) responseHeaders).put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), (Map) responseHeaders); } catch (IOException e) { StringBuilder sb = new StringBuilder(); BufferedReader rd = null; rd = new BufferedReader( new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } return new HttpResponse(sb.toString(), urlConnection.getResponseCode()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:org.wso2.carbon.esb.mediator.test.iterate.IterateJsonPathTest.java
private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws AutomationFrameworkException, IOException { HttpURLConnection urlConnection = null; try {/*from w ww . j av a2s . co m*/ urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new AutomationFrameworkException( "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); urlConnection.setReadTimeout(10000); for (Map.Entry<String, String> e : headers.entrySet()) { urlConnection.setRequestProperty(e.getKey(), e.getValue()); } OutputStream out = urlConnection.getOutputStream(); Writer writer = null; try { writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); } catch (IOException e) { throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e); } finally { if (writer != null) { writer.close(); } } StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Object responseHeaders = new HashMap(); String key; while (itr.hasNext()) { key = itr.next(); if (key != null) { ((Map) responseHeaders).put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), (Map) responseHeaders); } catch (IOException e) { StringBuilder sb = new StringBuilder(); BufferedReader rd = null; rd = new BufferedReader( new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); return new HttpResponse(sb.toString(), urlConnection.getResponseCode()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * //from ww w . j a va 2 s . com * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception { HttpURLConnection urlConnection = null; try {/*from w ww. j a v a 2 s.com*/ urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("DELETE"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); urlConnection.setRequestProperty(key, headers.get(key)); } } // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception { HttpURLConnection urlConnection = null; try {/*from w w w.jav a 2 s . com*/ urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); urlConnection.setRequestProperty(key, headers.get(key)); } } OutputStream out = urlConnection.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:com.linkbubble.util.Util.java
public static String downloadJSONAsString(String url, int timeout) { try {/*from ww w . j ava 2 s . c o m*/ URL u = new URL(url); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.connect(); int status = connection.getResponseCode(); switch (status) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); return sb.toString(); } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return null; }