List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:org.activiti.rest.content.service.api.BaseSpringContentRestTestCase.java
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) { CloseableHttpResponse response = null; try {//from www.j av a 2 s. c o m if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) { // Revert to default content-type request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); } response = client.execute(request); Assert.assertNotNull(response.getStatusLine()); int responseStatusCode = response.getStatusLine().getStatusCode(); if (expectedStatusCode != responseStatusCode) { log.info("Wrong status code : " + responseStatusCode + ", but should be " + expectedStatusCode); log.info("Response body: " + IOUtils.toString(response.getEntity().getContent())); } Assert.assertEquals(expectedStatusCode, responseStatusCode); httpResponses.add(response); return response; } catch (ClientProtocolException e) { Assert.fail(e.getMessage()); } catch (IOException e) { Assert.fail(e.getMessage()); } return null; }
From source file:org.mumod.util.ImageManager.java
public Bitmap fetchImage(String url) throws IOException { // Log.d(TAG, "Fetching image: " + url); HttpGet get = new HttpGet(url); HttpConnectionParams.setConnectionTimeout(get.getParams(), CONNECTION_TIMEOUT_MS); HttpConnectionParams.setSoTimeout(get.getParams(), SOCKET_TIMEOUT_MS); HttpResponse response;/* w w w.ja v a2 s .c o m*/ try { response = mClient.execute(get); } catch (ClientProtocolException e) { if (MustardApplication.DEBUG) Log.e(TAG, e.getMessage(), e); throw new IOException("Invalid client protocol."); } if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Non OK response: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); BufferedInputStream bis = new BufferedInputStream(entity.getContent(), 8 * 1024); Bitmap bitmap = BitmapFactory.decodeStream(bis); bis.close(); return bitmap; }
From source file:org.mobicents.servlet.restcomm.provisioning.number.bandwidth.BandwidthNumberProvisioningManager.java
protected String executeRequest(HttpUriRequest request) throws IOException { String response = ""; try {//from w w w .jav a 2 s . co m HttpResponse httpResponse = httpClient.execute(request); response = httpResponse.getEntity() != null ? EntityUtils.toString(httpResponse.getEntity()) : ""; } catch (ClientProtocolException cpe) { logger.error("Error in execute request: " + cpe.getMessage()); throw new IOException(cpe); } return response; }
From source file:net.evecom.androidecssp.activity.taskresponse.TaskListActivity.java
/** * //from w ww.j a va 2 s.c o m */ private void initlist() { new Thread(new Runnable() { @Override public void run() { Message message = new Message(); try { HashMap<String, String> hashMap = new HashMap<String, String>(); String url = ""; if (!ifmytask) { hashMap.put("eventId", eventInfo.get("id").toString()); hashMap.put("projectId", projectInfo.get("id").toString()); url = "jfs/ecssp/mobile/taskresponseCtr/getTaskByEventIdAndProjectId"; } else { hashMap.put("deptid", ShareUtil.getString(instance, "PASSNAME", "orgid", "")); hashMap.put("userid", ShareUtil.getString(instance, "PASSNAME", "userid", "")); url = "jfs/ecssp/mobile/taskresponseCtr/getTaskByDeptIdAndUserId"; } System.out.println(hashMap.values().toArray().toString()); resutArray = connServerForResultPost(url, hashMap); } catch (ClientProtocolException e) { message.what = MESSAGETYPE_02; Log.e("mars", e.getMessage()); } catch (IOException e) { message.what = MESSAGETYPE_02; Log.e("mars", e.getMessage()); } if (resutArray.length() > 0) { try { taskInfos = getObjsInfo(resutArray); if (null == taskInfos) { message.what = MESSAGETYPE_02; } else { message.what = MESSAGETYPE_01; } } catch (JSONException e) { message.what = MESSAGETYPE_02; Log.e("mars", e.getMessage()); } } else { message.what = MESSAGETYPE_02; } Log.v("mars", resutArray); eventListHandler.sendMessage(message); } }).start(); }
From source file:eu.europeanaconnect.erds.HTTPResolver.java
/** * Fetches the URL out of the header of the redirect response * of the remote resolver using the "Location" attribute * // w w w .j a v a 2s .c o m * @see DataProvider#getResponse(ResolverRequest) * @since 17.03.2010 */ @Override public ResolverResponse getResponse(ResolverRequest resolverRequest) throws ResolverException { this.httpClient = new DefaultHttpClient(); ResolverResponse resolverResponse = new ResolverResponse(); HttpResponse httpResponse = null; String url = getRequestUrl(resolverRequest); logger.debug("URL = " + url); HttpGet getMethod = new HttpGet(url); this.httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); this.httpClient.getParams().setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, false); try { httpResponse = this.httpClient.execute(getMethod); logger.debug("Operation GET successfull"); } catch (ClientProtocolException e) { logger.error("A ClientProtocolException occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.HTTP_PROTOCOL_ERROR, e); } catch (IOException e) { logger.error("An IOException occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.IO_ERROR, e); } catch (RuntimeException e) { logger.error("A RuntimeException occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.SEVERE_RUNTIME_ERROR, e); } catch (Exception e) { logger.error("An Exception occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.UNKNOWN_ERROR, e); } StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("HTTP Status-code: " + statusCode); if ((statusCode > 299) && (statusCode < 400)) { //It is a redirect See: http://www.w3.org/Protocols/rfc2616/rfc2616.html logger.debug("Analyzing HTTP Header"); //logger.debug(getMethod.) if (!httpResponse.containsHeader("Location")) { logger.error("Header does not contain Location attribute!"); throw new ResolverException(this.id, ResolverExceptionCode.NO_REDIRECT_ERROR); } logger.debug("Analyzing redirect location"); Header location = httpResponse.getFirstHeader("Location"); if (location == null) { logger.error("No redirect header for URL: " + url); throw new ResolverException(this.id, ResolverExceptionCode.NO_REDIRECT_ERROR); } logger.debug("Location: " + location.getValue()); resolverResponse.setUrl(location.getValue()); } else { //It should be a redirect but it is NOT! Analyse the Response handleHttpErrorCodes(statusCode); } //TODO: find a better way this.httpClient.getConnectionManager().closeExpiredConnections(); this.httpClient.getConnectionManager().closeIdleConnections(5, TimeUnit.SECONDS); return resolverResponse; }
From source file:httputils.RavelloHttpClient.java
public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay, String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized) throws RavelloException, InterruptedException { JsonObject value = null;// w ww. j ava2 s.c o m HttpResponse response = null; try { response = this.getBlueprint(blueprintId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: " + response.getStatusLine().toString()); } JsonObject vmTemp = HttpUtil.convertResponseToJson(response); EntityUtils.consume(response.getEntity()); JsonBuilderFactory factory = Json.createBuilderFactory(null); Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator(); JsonObjectBuilder builder = factory.createObjectBuilder(); Map.Entry<String, JsonValue> ent; while (it.hasNext()) { ent = it.next(); if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) { builder.add(ent.getKey(), ent.getValue()); } } builder.add("name", applicationName); value = builder.build(); vmTemp = null; response = this.createApplication(value); this.verifyResponseAndConsume(response, "Failed to create application - error: "); value = HttpUtil.convertResponseToJson(response); EntityUtils.consumeQuietly(response.getEntity()); int appId = value.getInt("id"); if (costOptimized) { value = factory.createObjectBuilder().add("startAllVms", startAllVms).build(); } else { value = factory.createObjectBuilder().add("startAllVms", startAllVms) .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion) .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build(); } response = this.post("/applications/" + appId + "/publish", value); this.verifyResponseAndConsume(response, "Failed to publish application - error: "); value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build(); response = this.post("/applications/" + appId + "/setExpiration", value); if (!HttpUtil.verifyResponseAndConsume(response)) { throw new RavelloException("Failed to set expiration time for application - error: " + response.getStatusLine().toString() + "\n" + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED"); } if (!startAllVms) { response = this.getApplication(appId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException( "Failed to get application status - error: " + response.getStatusLine().toString()); } value = HttpUtil.convertResponseToJson(response); return value; } String state; JsonArray jArr; boolean allStarted; while (true) { allStarted = true; response = this.getApplication(appId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException( "Failed to get application status - error: " + response.getStatusLine().toString()); } value = HttpUtil.convertResponseToJson(response); jArr = value.getJsonObject("deployment").getJsonArray("vms"); for (int jt = 0; jt < jArr.size(); jt++) { state = jArr.getJsonObject(jt).getString("state"); allStarted = state.equals("STARTED"); if (state.equals("ERROR")) { throw new RavelloException( "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start"); } if (!allStarted) { break; } } if (allStarted) { break; } else { EntityUtils.consumeQuietly(response.getEntity()); Thread.sleep(20000); } } } catch (ClientProtocolException e) { throw new RavelloException("ClientProtocolException - " + e.getMessage()); } catch (IOException e) { throw new RavelloException("IOException - " + e.getMessage()); } catch (NullPointerException e) { throw new RavelloException("NullPointerException - " + e.getMessage()); } Thread.sleep(startupDelay * 1000); return value; }
From source file:com.sourcey.materiallogindemo.PostItemActivity.java
public String getJSONUrl(String url, List<NameValuePair> params) { StringBuilder str = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); try {/* w ww .ja v a2s. com*/ httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = client.execute(httpPost); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { // Download OK HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { str.append(line); } } else { Log.e("Log", "Failed to download file.."); } } catch (ClientProtocolException e) { e.getMessage(); } catch (IOException e) { e.getMessage(); } return str.toString(); }
From source file:com.naryx.tagfusion.cfm.tag.cfCONTENT.java
private void remoteFetchUrl(cfStructData props, cfSession _Session) throws cfmRunTimeException { if (!props.containsKey("url")) throw newRunTimeException("'remote'.type=http; minimum keys are url"); CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from ww w . ja v a 2 s.co m*/ HttpGet httpget = new HttpGet(props.getData("url").getString()); CloseableHttpResponse response = httpclient.execute(httpget); try { if (response.getStatusLine().getStatusCode() != 200) { _Session.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); return; } HttpEntity entity = response.getEntity(); if (entity != null) { _Session.setContentType(entity.getContentType().getValue()); InputStream in = entity.getContent(); try { byte[] buffer = new byte[65536]; int readCount = 0; while ((readCount = in.read(buffer)) != -1) { _Session.write(buffer, 0, readCount); _Session.pageFlush(); } } catch (IOException ex) { throw ex; } finally { in.close(); } } } finally { response.close(); } } catch (ClientProtocolException e) { throw newRunTimeException(e.getMessage()); } catch (IOException e) { throw newRunTimeException(e.getMessage()); } finally { try { httpclient.close(); } catch (IOException e) { } } }
From source file:com.liato.bankdroid.banking.banks.Lansforsakringar.java
public Urllib login() throws LoginException, BankException { try {// www . j a va2s.c om LoginPackage lp = preLogin(); String response = urlopen.open(lp.getLoginTarget(), lp.getPostData()); if (response.contains("Felaktig inloggning")) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } Matcher matcher = reToken.matcher(response); if (!matcher.find()) { throw new BankException(res.getText(R.string.unable_to_find).toString() + " token."); } mRequestToken = matcher.group(1); matcher = reUrl.matcher(response); if (!matcher.find()) { throw new BankException(res.getText(R.string.unable_to_find).toString() + " accounts url."); } host = urlopen.getCurrentURI().split("/")[2]; accountsUrl = Html.fromHtml(matcher.group(1)).toString() + "&_token=" + mRequestToken; if (!accountsUrl.contains("https://")) { accountsUrl = "https://" + host + accountsUrl; } } catch (ClientProtocolException e) { throw new BankException(e.getMessage()); } catch (IOException e) { throw new BankException(e.getMessage()); } return urlopen; }
From source file:org.bonitasoft.engine.api.HTTPServerAPI.java
private String executeHttpPost(final Map<String, Serializable> options, final String apiInterfaceName, final String methodName, final List<String> classNameParameters, final Object[] parametersValues, final XStream xstream) throws UnsupportedEncodingException, IOException, ClientProtocolException { final HttpPost httpost = createHttpPost(options, apiInterfaceName, methodName, classNameParameters, parametersValues, xstream);/*from w w w.j a va 2 s. c om*/ try { return httpclient.execute(httpost, RESPONSE_HANDLER); } catch (final ClientProtocolException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage() + System.getProperty("line.separator") + "httpost = <" + httpost + ">"); } throw e; } }