List of usage examples for org.apache.http.client.methods HttpUriRequest abort
void abort() throws UnsupportedOperationException;
From source file:com.bbxiaoqu.api.ApiAsyncTask.java
@Override protected Object doInBackground(Void... params) { if (!Utils.isNetworkAvailable(mContext)) { return TIMEOUT_ERROR; }//w ww . jav a 2s. co m String requestUrl = MarketAPI.API_URLS[mReuqestAction]; requestUrl = GETURL(requestUrl, mParameter);//?GETURL HttpEntity requestEntity = null; try { requestEntity = ApiRequestFactory.getRequestEntity(mReuqestAction, mParameter); } catch (UnsupportedEncodingException e) { Utils.D("OPPS...This device not support UTF8 encoding.[should not happend]"); return BUSSINESS_ERROR; } Object result = null; HttpResponse response = null; HttpUriRequest request = null; try { request = ApiRequestFactory.getRequest(requestUrl, mReuqestAction, requestEntity); mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);// mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);// response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); Utils.D("requestUrl " + requestUrl + " statusCode: " + statusCode); if (HttpStatus.SC_OK != statusCode) { // ? return statusCode; } result = ApiResponseFactory.getResponse(mContext, mReuqestAction, response); // ?API Response?BUSSINESS_ERROR?610 return result == null ? BUSSINESS_ERROR : result; } catch (IOException e) { Utils.D("Market API encounter the IO exception[mostly is timeout exception]", e); return TIMEOUT_ERROR; } finally { // release the connection if (request != null) { request.abort(); } if (response != null) { try { HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } catch (IOException e) { Utils.D("release low-level resource error"); } } } }
From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java
@NotNull private <T> T processResponse(@NotNull HttpUriRequest request, @NotNull final Class<T> clazz) throws IOException { setDefaultHeaders(request);// w ww .j a v a 2 s . c o m try { logRequest(request, null); final HttpResponse execute = myClient.execute(request); if (execute.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { logFailedResponse(request, null, execute); throw new IOException("Failed to complete request to GitHub. Status: " + execute.getStatusLine()); } final HttpEntity entity = execute.getEntity(); if (entity == null) { logFailedResponse(request, null, execute); throw new IOException( "Failed to complete request to GitHub. Empty response. Status: " + execute.getStatusLine()); } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); entity.writeTo(bos); final String json = bos.toString("utf-8"); LOG.debug("Parsing json for " + request.getURI().toString() + ": " + json); return myGson.fromJson(json, clazz); } finally { EntityUtils.consume(entity); } } finally { request.abort(); } }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
private void doHttp(HttpUriRequest request, OutputStream os) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = null; try {//from w w w . j a va 2 s. c om instream = entity.getContent(); IOUtils.copy(instream, os); } catch (RuntimeException ex) { request.abort(); throw ex; } finally { try { instream.close(); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } httpclient.getConnectionManager().shutdown(); } }
From source file:co.tuzza.clicksend4j.client.ClickSendSmsClient.java
public SmsResults sendSms(SMS sms) throws Exception { List<NameValuePair> params = parseSMS(sms); String response = null;//from www . ja v a2 s . co m for (int pass = 1; pass <= 3; pass++) { HttpUriRequest method; HttpPost httpPost = new HttpPost(baseUrl + Definitions.SEND_SMS_URL_JSON); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); httpPost.setHeader("Authorization", "Basic " + this.authHeader); method = httpPost; String url = baseUrl + "?" + URLEncodedUtils.format(params, "utf-8"); try { if (httpClient == null) { httpClient = HttpClientUtils.getInstance(connectionTimeout, socketTimeout).getHttpClient(); } HttpResponse httpResponse = httpClient.execute(method); int status = httpResponse.getStatusLine().getStatusCode(); if (status != 200) { if (status == 401) { throw new Exception("got a 401 response from ClickSend-HTTP for url [ " + url + " ] - Authorisation failed"); } throw new Exception("got a non-200 response [ " + status + " ] from ClickSend-HTTP for url [ " + url + " ] "); } response = new BasicResponseHandler().handleResponse(httpResponse); log.info("SMS SEND CLICKSEND-HTTP URL [ " + url + " ] -- response [ " + response + " ] "); break; } catch (Exception ex) { method.abort(); log.info("communication failure", ex); String exceptionMsg = ex.getMessage(); if (exceptionMsg.contains("Read timed out")) { log.info( "we're still connected, but the target did not respond in a timely manner .. drop ..."); } else { if (pass < 2) { log.info("... re-establish http client ..."); this.httpClient = null; continue; } } SmsResults results = new SmsResults(); SmsResult smsResult = new SmsResult(); smsResult.setResult("LOCAL500"); smsResult.setErrorText("Failed to communicate with CLICKSEND-HTTP url [ " + url + " ] ..." + ex); smsResult.setStatusDescription(Definitions.SEND_SMS_RESPONSE_CODES_MAP.get("LOCAL500")); results.addSmsResult(smsResult); return results; } } JsonParser jsonParser = new JsonParser(); SmsResults smsResults = jsonParser.parseJson(response, SmsResults.class); return smsResults; }
From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java
public VerifyResult verify(final String number, final String brand, final String from, final int length, final Locale locale, final LineType type) throws IOException, SAXException { if (number == null || brand == null) throw new IllegalArgumentException("number and brand parameters are mandatory."); if (length > 0 && length != 4 && length != 6) throw new IllegalArgumentException("code length must be 4 or 6."); log.debug("HTTP-Number-Verify Client .. to [ " + number + " ] brand [ " + brand + " ] "); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("api_key", this.apiKey)); params.add(new BasicNameValuePair("api_secret", this.apiSecret)); params.add(new BasicNameValuePair("number", number)); params.add(new BasicNameValuePair("brand", brand)); if (from != null) params.add(new BasicNameValuePair("sender_id", from)); if (length > 0) params.add(new BasicNameValuePair("code_length", String.valueOf(length))); if (locale != null) params.add(/*from ww w.j a va2 s. c o m*/ new BasicNameValuePair("lg", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase())); if (type != null) params.add(new BasicNameValuePair("require_type", type.toString())); String verifyBaseUrl = this.baseUrl + PATH_VERIFY; // Now that we have generated a query string, we can instanciate a HttpClient, // construct a POST method and execute to submit the request String response = null; for (int pass = 1; pass <= 2; pass++) { HttpPost httpPost = new HttpPost(verifyBaseUrl); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpUriRequest method = httpPost; String url = verifyBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8"); try { if (this.httpClient == null) this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout) .getNewHttpClient(); HttpResponse httpResponse = this.httpClient.execute(method); int status = httpResponse.getStatusLine().getStatusCode(); if (status != 200) throw new Exception( "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] "); response = new BasicResponseHandler().handleResponse(httpResponse); log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] "); break; } catch (Exception e) { method.abort(); log.info("communication failure: " + e); String exceptionMsg = e.getMessage(); if (exceptionMsg.indexOf("Read timed out") >= 0) { log.info( "we're still connected, but the target did not respond in a timely manner .. drop ..."); } else { if (pass == 1) { log.info("... re-establish http client ..."); this.httpClient = null; continue; } } // return a COMMS failure ... return new VerifyResult(BaseResult.STATUS_COMMS_FAILURE, null, "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true); } } Document doc; synchronized (this.documentBuilder) { doc = this.documentBuilder.parse(new InputSource(new StringReader(response))); } Element root = doc.getDocumentElement(); if (!"verify_response".equals(root.getNodeName())) throw new IOException("No valid response found [ " + response + "] "); return parseVerifyResult(root); }
From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java
public SearchResult[] search(String... requestIds) throws IOException, SAXException { if (requestIds == null || requestIds.length == 0) throw new IllegalArgumentException("request ID parameter is mandatory."); if (requestIds.length > MAX_SEARCH_REQUESTS) throw new IllegalArgumentException("too many request IDs. Max is " + MAX_SEARCH_REQUESTS); log.debug("HTTP-Number-Verify-Search Client .. for [ " + Arrays.toString(requestIds) + " ] "); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("api_key", this.apiKey)); params.add(new BasicNameValuePair("api_secret", this.apiSecret)); if (requestIds.length == 1) { params.add(new BasicNameValuePair("request_id", requestIds[0])); } else {//from ww w. j a va 2s . co m for (String requestId : requestIds) params.add(new BasicNameValuePair("request_ids", requestId)); } String verifySearchBaseUrl = this.baseUrl + PATH_VERIFY_SEARCH; // Now that we have generated a query string, we can instanciate a HttpClient, // construct a POST method and execute to submit the request String response = null; for (int pass = 1; pass <= 2; pass++) { HttpPost httpPost = new HttpPost(verifySearchBaseUrl); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpUriRequest method = httpPost; String url = verifySearchBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8"); try { if (this.httpClient == null) this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout) .getNewHttpClient(); HttpResponse httpResponse = this.httpClient.execute(method); int status = httpResponse.getStatusLine().getStatusCode(); if (status != 200) throw new Exception( "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] "); response = new BasicResponseHandler().handleResponse(httpResponse); log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] "); break; } catch (Exception e) { method.abort(); log.info("communication failure: " + e); String exceptionMsg = e.getMessage(); if (exceptionMsg.indexOf("Read timed out") >= 0) { log.info( "we're still connected, but the target did not respond in a timely manner .. drop ..."); } else { if (pass == 1) { log.info("... re-establish http client ..."); this.httpClient = null; continue; } } // return a COMMS failure ... return new SearchResult[] { new SearchResult(BaseResult.STATUS_COMMS_FAILURE, null, null, null, null, 0, null, null, null, null, null, null, null, "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true) }; } } Document doc; synchronized (this.documentBuilder) { doc = this.documentBuilder.parse(new InputSource(new StringReader(response))); } Element root = doc.getDocumentElement(); if ("verify_response".equals(root.getNodeName())) { // error response VerifyResult result = parseVerifyResult(root); return new SearchResult[] { new SearchResult(result.getStatus(), result.getRequestId(), null, null, null, 0, null, null, null, null, null, null, null, result.getErrorText(), result.isTemporaryError()) }; } else if (("verify_request").equals(root.getNodeName())) { return new SearchResult[] { parseSearchResult(root) }; } else if ("verification_requests".equals(root.getNodeName())) { List<SearchResult> results = new ArrayList<>(); NodeList fields = root.getChildNodes(); for (int i = 0; i < fields.getLength(); i++) { Node node = fields.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; if ("verify_request".equals(node.getNodeName())) results.add(parseSearchResult((Element) node)); } return results.toArray(new SearchResult[results.size()]); } else { throw new IOException("No valid response found [ " + response + "] "); } }
From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java
public CheckResult check(final String requestId, final String code, final String ipAddress) throws IOException, SAXException { if (requestId == null || code == null) throw new IllegalArgumentException("request ID and code parameters are mandatory."); log.debug("HTTP-Number-Verify-Check Client .. for [ " + requestId + " ] code [ " + code + " ] "); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("api_key", this.apiKey)); params.add(new BasicNameValuePair("api_secret", this.apiSecret)); params.add(new BasicNameValuePair("request_id", requestId)); params.add(new BasicNameValuePair("code", code)); if (ipAddress != null) params.add(new BasicNameValuePair("ip_address", ipAddress)); String verifyCheckBaseUrl = this.baseUrl + PATH_VERIFY_CHECK; // Now that we have generated a query string, we can instanciate a HttpClient, // construct a POST method and execute to submit the request String response = null;//from w w w . j a va 2 s.c o m for (int pass = 1; pass <= 2; pass++) { HttpPost httpPost = new HttpPost(verifyCheckBaseUrl); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpUriRequest method = httpPost; String url = verifyCheckBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8"); try { if (this.httpClient == null) this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout) .getNewHttpClient(); HttpResponse httpResponse = this.httpClient.execute(method); int status = httpResponse.getStatusLine().getStatusCode(); if (status != 200) throw new Exception( "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] "); response = new BasicResponseHandler().handleResponse(httpResponse); log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] "); break; } catch (Exception e) { method.abort(); log.info("communication failure: " + e); String exceptionMsg = e.getMessage(); if (exceptionMsg.indexOf("Read timed out") >= 0) { log.info( "we're still connected, but the target did not respond in a timely manner .. drop ..."); } else { if (pass == 1) { log.info("... re-establish http client ..."); this.httpClient = null; continue; } } // return a COMMS failure ... return new CheckResult(BaseResult.STATUS_COMMS_FAILURE, null, 0, null, "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true); } } Document doc; synchronized (this.documentBuilder) { doc = this.documentBuilder.parse(new InputSource(new StringReader(response))); } Element root = doc.getDocumentElement(); if (!"verify_response".equals(root.getNodeName())) throw new IOException("No valid response found [ " + response + "] "); String eventId = null; int status = -1; float price = -1; String currency = null; String errorText = null; NodeList fields = root.getChildNodes(); for (int i = 0; i < fields.getLength(); i++) { Node node = fields.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; String name = node.getNodeName(); if ("event_id".equals(name)) { eventId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("status".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); try { if (str != null) status = Integer.parseInt(str); } catch (NumberFormatException e) { log.error("xml parser .. invalid value in <status> node [ " + str + " ] "); status = BaseResult.STATUS_INTERNAL_ERROR; } } else if ("price".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); try { if (str != null) price = Float.parseFloat(str); } catch (NumberFormatException e) { log.error("xml parser .. invalid value in <price> node [ " + str + " ] "); } } else if ("currency".equals(name)) { currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("error_text".equals(name)) { errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } } if (status == -1) throw new IOException("Xml Parser - did not find a <status> node"); // Is this a temporary error ? boolean temporaryError = (status == BaseResult.STATUS_THROTTLED || status == BaseResult.STATUS_INTERNAL_ERROR); return new CheckResult(status, eventId, price, currency, errorText, temporaryError); }
From source file:org.bibimbap.shortcutlink.RestClient.java
/** * Execute the REST subtasks/* www. ja v a 2 s. co m*/ */ protected RestClientRequest[] doInBackground(RestClientRequest... params) { // HttpClient that is configured with reasonable default settings and registered schemes for Android final AndroidHttpClient httpClient = AndroidHttpClient.newInstance(RestClient.class.getSimpleName()); for (int index = 0; index < params.length; index++) { RestClientRequest rcr = params[index]; HttpUriRequest httprequest = null; try { HttpResponse httpresponse = null; HttpEntity httpentity = null; // initiating publishProgress(params.length, index, RestfulState.DS_INITIATING); switch (rcr.getHttpRequestType()) { case HTTP_PUT: httprequest = new HttpPut(rcr.getURI()); break; case HTTP_POST: httprequest = new HttpPost(rcr.getURI()); break; case HTTP_DELETE: httprequest = new HttpDelete(rcr.getURI()); break; case HTTP_GET: default: // default to HTTP_GET httprequest = new HttpGet(rcr.getURI()); break; } // resting publishProgress(params.length, index, RestfulState.DS_ONGOING); if ((httpresponse = httpClient.execute(httprequest)) != null) { if ((httpentity = httpresponse.getEntity()) != null) { rcr.setResponse(EntityUtils.toByteArray(httpentity)); } } // success publishProgress(params.length, index, RestfulState.DS_SUCCESS); } catch (Exception ioe) { Log.i(TAG, ioe.getClass().getSimpleName()); // clear out the response rcr.setResponse(null); // abort the request on failure httprequest.abort(); // failed publishProgress(params.length, index, RestfulState.DS_FAILED); } } // close the connection if (httpClient != null) httpClient.close(); return params; }
From source file:com.wst.cls.HTTPBaseIO.java
/** * ??/*w ww .java2s.c o m*/ * * @param urlpath ? * @param method Method.get or Method.post * @param params ? * @param charset HTTP.UTF_8 * @param isAutoRedirect * ??Headerlocationlocation?? * @param isCloseConn ? * @return null??HTML * @throws ClientProtocolException * @throws IOException */ public String doSendBase(String urlpath, Method method, HttpEntity params, String charset, boolean isAutoRedirect, boolean isCloseConn) throws ClientProtocolException, IOException { String responseBody = null; HttpUriRequest httpgetpost = null; statuscode = HttpStatus.SC_NO_CONTENT; try { if (httpclient == null || isClosedConn()) { httpclient = new DefaultHttpClient(); } if (proxy != null) { httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (method == Method.post) { httpgetpost = new HttpPost(urlpath); if (params != null) { ((HttpPost) httpgetpost).setEntity(params); } } else { if (params != null) { urlpath += "?" + inputStream2String(params.getContent(), charset); } httpgetpost = new HttpGet(urlpath); } HttpResponse response = httpclient.execute(httpgetpost); statuscode = response.getStatusLine().getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = response.getFirstHeader("location"); if (header != null) { newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } if (isAutoRedirect) { httpgetpost.abort(); httpgetpost = null; responseBody = doSendBase(newuri, Method.get, null, charset, true, false); } } } else if (statuscode == HttpStatus.SC_OK) { responseBody = inputStream2String(response.getEntity().getContent(), charset); } } catch (ClientProtocolException e) { throw e; } catch (IOException e) { throw e; } catch (UnsupportedOperationException e) { e.printStackTrace(); } finally { if (httpgetpost != null) { httpgetpost.abort(); httpgetpost = null; } closeConn(isCloseConn); } return responseBody; }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
private void doHttp(HttpUriRequest request, CouchJSONConverter converter) throws Exception { HttpClient httpclient = new DefaultHttpClient(); // Execute the request HttpResponse response = httpclient.execute(request); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { InputStream instream = null; try {//w w w . ja va2 s.co m instream = entity.getContent(); converter.setInputStream(instream); converter.convert(); } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. request.abort(); throw ex; } finally { // Closing the input stream will trigger connection release try { instream.close(); } catch (IOException ex) { ex.printStackTrace(); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }