List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams
public BasicHttpParams()
From source file:at.alladin.rmbt.client.helper.JSONParser.java
public JSONObject getURL(final URI uri) { JSONObject jObj = null;//from w ww . jav a 2s. c o m String responseBody; try { final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 20000); HttpConnectionParams.setSoTimeout(params, 20000); final HttpClient client = new DefaultHttpClient(params); final HttpGet httpget = new HttpGet(uri); final ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseBody = client.execute(httpget, responseHandler); // try parse the string to a JSON object try { jObj = new JSONObject(responseBody); } catch (final JSONException e) { writeErrorList("Error parsing JSON " + e.toString()); } } catch (final UnsupportedEncodingException e) { writeErrorList("Wrong encoding"); // e.printStackTrace(); } catch (final HttpResponseException e) { writeErrorList( "Server responded with Code " + e.getStatusCode() + " and message '" + e.getMessage() + "'"); } catch (final ClientProtocolException e) { writeErrorList("Wrong Protocol"); // e.printStackTrace(); } catch (final IOException e) { writeErrorList("IO Exception"); e.printStackTrace(); } // return JSONObject return jObj; }
From source file:ca.sqlpower.enterprise.ClientSideSessionUtils.java
public static HttpClient createHttpClient(SPServerInfo serviceInfo, CookieStore cookieStore) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 2000); DefaultHttpClient httpClient = new DefaultHttpClient(params); httpClient.setCookieStore(cookieStore); httpClient.getCredentialsProvider().setCredentials( new AuthScope(serviceInfo.getServerAddress(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(serviceInfo.getUsername(), serviceInfo.getPassword())); return httpClient; }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
static public void main(String... args) throws Exception { if (args.length < 1) { System.err.println("You must specify an action"); System.exit(-1);/*w ww . j ava2 s.c om*/ return; } String action = args[0]; if (action.equalsIgnoreCase("initializePairing")) { if (args.length < 5) { System.err.println("You must specify a location ID"); System.exit(-2); return; } String endpoint = args[1]; String locationId = args[2]; String apiKeyId = args[3]; String apiKeySecret = args[4]; HashMap<String, Object> act = new HashMap<String, Object>(); act.put("action", "initializePairing"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPut method = new HttpPut(endpoint + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : "--no code--"); } else { System.err.println("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else if (action.equalsIgnoreCase("create")) { if (args.length < 7) { System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET"); System.exit(-2); return; } String endpoint = args[1]; String name = args[2]; String description = args[3]; String tz = args[4]; String apiKeyId = args[5]; String apiKeySecret = args[6]; HashMap<String, Object> lstate = new HashMap<String, Object>(); lstate.put("name", name); lstate.put("description", description); lstate.put("timeZone", tz); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPost method = new HttpPost(endpoint + "/location"); long timestamp = System.currentTimeMillis(); System.out.println( "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : "--no location--"); } else { System.err.println("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else { System.err.println("No such action: " + action); System.exit(-3); } }
From source file:net.line2soft.preambul.utils.Network.java
/** * Downloads a file from the Internet/*w w w . jav a 2s . com*/ * @param address The URL of the file * @param dest The destination directory * @return The queried file * @throws IOException HTTP connection error, or writing error */ public static File download(URL address, File dest) throws IOException { File result = null; InputStream in = null; BufferedOutputStream out = null; //Open streams try { HttpGet httpGet = new HttpGet(address.toExternalForm()); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 4000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); httpClient.setParams(httpParameters); HttpResponse response = httpClient.execute(httpGet); //Launch streams for download in = new BufferedInputStream(response.getEntity().getContent()); String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1); File tmp = new File(dest.getPath() + File.separator + filename); out = new BufferedOutputStream(new FileOutputStream(tmp)); //Test if connection is OK if (response.getStatusLine().getStatusCode() / 100 == 2) { //Download and write try { int byteRead = in.read(); while (byteRead >= 0) { out.write(byteRead); byteRead = in.read(); } result = tmp; } catch (IOException e) { throw new IOException("Error while writing file: " + e.getMessage()); } } } catch (IOException e) { e.printStackTrace(); throw new IOException("Error while downloading: " + e.getMessage()); } finally { //Close streams if (out != null) { out.close(); } if (in != null) { in.close(); } } return result; }
From source file:net.sarangnamu.common.network.BkHttp.java
public void setTimeout(int connTimeout, int socketTimeout) { if (http == null) { return;/*w ww . ja v a2 s . com*/ } HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connTimeout); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); http.setParams(httpParameters); }
From source file:org.mobiletrial.license.connect.RestClient.java
public void post(final String path, final JSONObject requestJson, final OnRequestFinishedListener listener) { Thread t = new Thread() { public void run() { Looper.prepare(); //For Preparing Message Pool for the child Thread // Register Schemes for http and https final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); HttpClient client = new DefaultHttpClient(cm, params); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit HttpResponse response;/*from ww w . j a va 2 s . c o m*/ try { String urlStr = mServiceUrl.toExternalForm(); if (urlStr.charAt(urlStr.length() - 1) != '/') urlStr += "/"; urlStr += path; URI actionURI = new URI(urlStr); HttpPost post = new HttpPost(actionURI); StringEntity se = new StringEntity(requestJson.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = client.execute(post); /* Checking response */ if (response == null) { listener.gotError(ERROR_CONTACTING_SERVER); Log.w(TAG, "Error contacting licensing server."); return; } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(TAG, "An error has occurred on the licensing server."); listener.gotError(ERROR_SERVER_FAILURE); return; } /* Convert response to JSON */ InputStream in = response.getEntity().getContent(); //Get the data in the entity String responseStr = inputstreamToString(in); listener.gotResponse(responseStr); } catch (ClientProtocolException e) { Log.w(TAG, "ClientProtocolExeption: " + e.getLocalizedMessage()); e.printStackTrace(); } catch (IOException e) { Log.w(TAG, "Error on contacting server: " + e.getLocalizedMessage()); listener.gotError(ERROR_CONTACTING_SERVER); } catch (URISyntaxException e) { //This shouldn't happen Log.w(TAG, "Could not build URI.. Your service Url is propably not a valid Url: " + e.getLocalizedMessage()); e.printStackTrace(); } Looper.loop(); //Loop in the message queue } }; t.start(); }
From source file:com.core.ServerConnector.java
public static String GET(String endpoint, Map<String, String> params, Map<String, String> header) throws Exception { String result = null;/* w w w. j ava 2 s . c o m*/ StringBuilder bodyBuilder = new StringBuilder(endpoint).append("?"); 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.i("SCANTRANX", "URL:"+body); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(body); for (Entry<String, String> mm : header.entrySet()) { request.addHeader(mm.getKey(), mm.getValue()); } System.out.println("Raw Request:" + request); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); result = SystemUtil.convertStreamToString(instream); instream.close(); } return result; }
From source file:fedroot.dacs.http.DacsClientContext.java
/** * constructor for DacsClientContext;//from ww w . j ava 2 s. c o m * initializes HttpClient that will be used for this DacsContext, * sets legacy BROWSER_COMPATIBILITY mode to emulate typical browser behaviour. * In particular this is relied upon to ensure that cookies are sent when * hostname = cookie domainname. */ public DacsClientContext() { this(new BasicHttpParams()); }
From source file:neembuu.uploader.external.CheckMajorUpdate.java
/** * @deprecated version.xml is located in update.zip which is used to get list * of latest plugins/*from www . jav a 2 s .co m*/ */ @Deprecated private static String getVersionXmlOnline() throws IOException { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet("http://neembuuuploader.sourceforge.net/version.xml"); NULogger.getLogger().info("Checking for new version..."); HttpResponse response = httpclient.execute(httpget); return EntityUtils.toString(response.getEntity()); }