List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:org.dspace.submit.lookup.CrossRefService.java
public List<Record> search(Context context, Set<String> dois, String apiKey) throws HttpException, IOException, JDOMException, ParserConfigurationException, SAXException { List<Record> results = new ArrayList<Record>(); if (dois != null && dois.size() > 0) { for (String record : dois) { try { HttpGet method = null;// w w w . j a v a 2 s . com try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); try { URIBuilder uriBuilder = new URIBuilder("http://www.crossref.org/openurl/"); uriBuilder.addParameter("pid", apiKey); uriBuilder.addParameter("noredirect", "true"); uriBuilder.addParameter("id", record); method = new HttpGet(uriBuilder.build()); } catch (URISyntaxException ex) { throw new HttpException("Request not sent", ex); } // Execute the method. HttpResponse response = client.execute(method); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("Http call failed: " + statusLine); } Record crossitem; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder db = factory.newDocumentBuilder(); Document inDoc = db.parse(response.getEntity().getContent()); Element xmlRoot = inDoc.getDocumentElement(); Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result"); Element body = XMLUtils.getSingleElement(queryResult, "body"); Element dataRoot = XMLUtils.getSingleElement(body, "query"); crossitem = CrossRefUtils.convertCrossRefDomToRecord(dataRoot); results.add(crossitem); } catch (Exception e) { log.warn(LogManager.getHeader(context, "retrieveRecordDOI", record + " DOI is not valid or not exist: " + e.getMessage())); } } finally { if (method != null) { method.releaseConnection(); } } } catch (RuntimeException rt) { log.error(rt.getMessage(), rt); } } } return results; }
From source file:topoos.APIAccess.APICaller.java
/** * Initiates an operation on topoos API. * /* w w w . j a va 2 s. c om*/ * @param operation * Represents the operation to be executed * @param result * Represents a result returned from a query to API topoos * @throws IOException * @throws TopoosException */ public static void ExecuteOperation(APIOperation operation, APICallResult result, Integer service) throws IOException, TopoosException { HttpClient hc = new DefaultHttpClient(); if (!operation.ValidateParams()) throw new TopoosException(TopoosException.NOT_VALID_PARAMS); String OpURI = ""; switch (service) { case SERVICE_API: OpURI = GetURLAPItopoos() + operation.ConcatParams(); break; case SERVICE_PIC: OpURI = GetURLPICAPItopoos() + operation.ConcatParams(); break; case SERVICE_SOCIAL: OpURI = GetURLSOCIALAPItopoos() + operation.ConcatParams(); break; default: OpURI = GetURLAPItopoos() + operation.ConcatParams(); break; } if (Constants.DEBUGURL) { Log.d(Constants.TAG, OpURI); // appendLog(OpURI); } HttpPost post = new HttpPost(OpURI); // POST if (operation.getMethod().equals("POST")) { post.setEntity(operation.BodyParams()); } HttpResponse rp = hc.execute(post); HttpParams httpParams = hc.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS); HttpConnectionParams.setSoTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS); if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result.setResult(EntityUtils.toString(rp.getEntity())); if (Constants.DEBUGURL) { Log.d(Constants.TAG, result.getResult()); // appendLog(result.getResult()); } result.setError(null); result.setParameters(); } else { switch (rp.getStatusLine().getStatusCode()) { case 400: throw new TopoosException(TopoosException.ERROR400); case 405: throw new TopoosException(TopoosException.ERROR405); default: throw new TopoosException("Error: " + rp.getStatusLine().getStatusCode() + ""); } } }
From source file:cl.mmoscoso.geocomm.sync.GeoCommCreateRouteAsyncTask.java
@Override protected Boolean doInBackground(Void... params) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); try {/*from w ww . j av a 2 s .c o m*/ // Add your data Log.i(TAGNAME, "PUBLIC: " + this.is_public); Log.i(TAGNAME, "NAME: " + this.name); Log.i(TAGNAME, "DESC: " + this.desc); Log.i(TAGNAME, "OWNER: " + this.id_user); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("name", this.name)); nameValuePairs.add(new BasicNameValuePair("description", this.desc)); nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(this.id_user))); nameValuePairs.add(new BasicNameValuePair("public", Boolean.toString(this.is_public))); //nameValuePairs.add(new BasicNameValuePair("id", "1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); Log.i(TAGNAME, "ERROR: " + responseCode); switch (responseCode) { default: Log.i(TAGNAME, "ERROR"); //Toast.makeText(this.context,R.string.error_not200code, Toast.LENGTH_SHORT).show(); break; case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); Log.i(TAGNAME, responseBody); JSONObject jObj; try { Log.i(TAGNAME, "Status: " + this.is_public); jObj = new JSONObject(responseBody); this.status = jObj.getInt("status"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return true; }
From source file:cl.mmoscoso.geocomm.sync.GeoCommGetRoutesAsyncTask.java
@Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); Log.i(TAGNAME, "Try to connect to " + this.hostname); try {//from w ww. j a v a2s.com Log.i(TAGNAME, "Post Request"); HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); Log.i(TAGNAME, "CODE: " + responseCode); switch (responseCode) { default: //Toast.makeText(this.context,R.string.error_not200code, Toast.LENGTH_SHORT).show(); Log.i(TAGNAME, "Error"); break; case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); //Log.i(TAGNAME, responseBody); JSONObject jObj, ruta; try { Log.i(TAGNAME, "Reading JSONResponse"); //Log.i(TAGNAME, responseBody); jObj = new JSONObject(responseBody); for (int i = 0; i < jObj.length(); i++) { ruta = new JSONObject(jObj.getString(jObj.names().getString(i))); list_routes.add(new GeoCommRoute(ruta.getString("name"), ruta.getString("owner"), ruta.getInt("id"), ruta.getInt("totalPoints"), ruta.getString("description"), ruta.getBoolean("public"))); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block Log.e(TAGNAME, e.toString()); return false; } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAGNAME, e.toString()); return false; } return true; }
From source file:org.centum.android.communicators.QuizletCommunicator.java
private JSONObject getJSONObject(URI uri) throws IOException, JSONException { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android"); HttpGet request = new HttpGet(); request.setHeader("Content-Type", "text/plain; charset=utf-8"); request.setURI(uri);/* w w w .j av a 2 s .c o m*/ HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { stringBuffer.append(line + NL); } in.close(); return new JSONObject(stringBuffer.toString()); }
From source file:org.jasig.ssp.security.BasicAuthenticationRestTemplate.java
private HttpClient addClientAddress(HttpClient clientd, String clientIpAddress, Integer clientPort) { if (StringUtils.isNotBlank(clientIpAddress) && clientPort != null) { HttpHost proxy = new HttpHost(clientIpAddress, clientPort); clientd.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }//from w w w . j ava2 s . com return clientd; }
From source file:cl.mmoscoso.geocomm.sync.GeoCommLogInAsyncTask.java
@Override protected Boolean doInBackground(Void... params) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); try {/*from w ww . j a v a2s . c o m*/ // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("username", this.name)); nameValuePairs.add(new BasicNameValuePair("password", this.pass)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); //int responseCode = 201; switch (responseCode) { case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); //Log.i(TAGNAME, responseBody); JSONObject jObj, point; try { //Log.i(TAGNAME, "tamao: "+ responseBody); jObj = new JSONObject(responseBody); this.value_login = jObj.getInt("status"); this.id_user = jObj.getInt("id"); //Log.i(TAGNAME, "Value: "+ this.value_login ); //this.name_user = jObj.getString("name"); //this.id_user = jObj.getInt("id"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; default: Log.i(TAGNAME, "Error"); //Toast.makeText(this.context,"ERROR!!", Toast.LENGTH_SHORT).show(); break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return true; }
From source file:com.cloudbees.eclipse.core.ClickStartService.java
/** * @param templateId/* ww w . ja va 2s . c o m*/ * @param account * @param name * @return * @throws CloudBeesException */ public ClickStartCreateResponse create(String template, String account, String name) throws CloudBeesException { //* curl -i -X POST //"http://localhost:8080/api/apps/json/launch?account=michaelnealeclickstart2&name=nodecli&template=https://raw.github.com/CloudBees-community/nodejs-clickstart/master/clickstart.json" StringBuffer errMsg = new StringBuffer(); try { String url = CS_API_URL + "launch?account=" + account + "&name=" + name + "&template=" + template; HttpClient httpclient = Utils.getAPIClient(url); HttpParams params = httpclient.getParams(); // Override timeouts, this request can be long.. HttpConnectionParams.setConnectionTimeout(params, 6 * 60 * 1000); HttpConnectionParams.setSoTimeout(params, 6 * 60 * 1000); HttpPost get = Utils.jsonRequest(url, ""); applyAuth(get); System.out.println("Request URL: " + url); System.out.println( "curl --header \"Authorization: Basic NzgxNUI0MUQzRjREOTk2ODpVUDQzM1NURjFOQjlZRElFRytWSzk4RFhNQjBDSExPRko2WFlFQlRIMENBPQ==\" -i -X POST \"" + url + "\""); HttpResponse resp = httpclient.execute(get); String bodyResponse = Utils.getResponseBody(resp); System.out.println("JSON RESPONSE for the create command:\n" + bodyResponse); Gson g = Utils.createGson(); ClickStartCreateResponse r = g.fromJson(bodyResponse, ClickStartCreateResponse.class); checkForErrors(resp, r); return r; } catch (Exception e) { throw new CloudBeesException("Failed to create from template " + template + " for account " + account + " using name " + name + (errMsg.length() > 0 ? " (" + errMsg + ")" : ""), e); } }
From source file:com.jigarmjoshi.service.RestService.java
private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient(); // no response within 120 seconds client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120 * 1000); // this one causes a timeout if no connection is established within 5min client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300 * 1000); HttpResponse httpResponse;/* w w w. java2 s . c o m*/ try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException ex) { client.getConnectionManager().shutdown(); Log.e(RestService.class.getSimpleName(), "Failed to execute rest call ", ex); } catch (IOException ex) { client.getConnectionManager().shutdown(); Log.e(RestService.class.getSimpleName(), "Failed to execute rest call ", ex); } }
From source file:org.jboss.arquillian.android.drone.impl.SelendroidHelper.java
/** * Waits for Selendroid start. After installation and execution of instrumentation command, we repeatedly send http request * to status page to get response code of 200 - server is up and running and we can proceed safely. *//*from ww w . j a va 2 s .c o m*/ public void waitForServerHTTPStart() { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIME_OUT_SECONDS * 1000); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIME_OUT_SECONDS * 1000); HttpGet httpGet = new HttpGet(getSelendroidStatusURI()); boolean connectionSuccess = false; for (int i = NUM_CONNECTION_RETIRES; i > 0; i--) { try { HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { connectionSuccess = true; break; } logger.log(Level.INFO, "Response was not 200, response was: " + statusCode + ". Repeating " + i + " times."); } catch (ClientProtocolException e) { logger.log(Level.WARNING, e.getMessage()); } catch (IOException e) { logger.log(Level.WARNING, e.getMessage()); } } httpClient.getConnectionManager().shutdown(); if (!connectionSuccess) { throw new AndroidExecutionException("Unable to get successful connection from Selendroid http server."); } }