List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:net.evecom.androidecssp.activity.EventAddActivity.java
/** * /*ww w .j a v a 2 s. c om*/ * postdata * @author Mars zhang * @created 2015-11-10 4:13:51 * @param entity */ private void postdata(final HashMap<String, String> entity) { new Thread(new Runnable() { @Override public void run() { Message message = new Message(); try { saveResult = connServerForResultPost("jfs/ecssp/mobile/eventCtr/EventAdd", entity); } 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 (saveResult.length() > 0) { message.what = MESSAGETYPE_01; String eventId = ""; try { BaseModel eventInfo = getObjInfo(saveResult); if (null != eventInfo) { eventId = eventInfo.get("id"); } } catch (JSONException e) { Log.e("mars", e.getMessage()); } HashMap<String, String> map = new HashMap<String, String>(); map.put("eventId", eventId); postImage(map, fileList, "jfs/ecssp/mobile/eventCtr/eventFileSave"); } else { message.what = MESSAGETYPE_02; } Log.v("mars", saveResult); saveHandler.sendMessage(message); } }).start(); }
From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ReSTDelegateImpl.java
@Override public List<Object[]> getRows() { String queryUrl = (String) queryUrlProvider.call(); if (StringUtils.isBlank(queryUrl)) { return EMPTY_RESULT; }/*from w w w .j a v a2 s .c o m*/ HttpGet request = createQueryRequest(); try { HttpResponse response = httpClient.execute(request); expectAnyStatusCode(response, HttpStatus.SC_OK); return parser.getRows(response); } catch (ClientProtocolException e) { LOGGER.error("Error during restful query", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } catch (IOException e) { LOGGER.error("Error during restful query", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } finally { request.releaseConnection(); } }
From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ReSTDelegateImpl.java
@Override public void update(List<GenericItem> items, UpdateContext context) { context.requireRefresh();//from w w w.ja v a2s. c om try { for (GenericItem item : items) { if (item.isNewItem() || item.isModified()) { ReSTChangeConfig changeConfig = findChangeConfig(item); ReSTChangeMethodConfig method = findRequestMethod(item); if (method == ReSTChangeMethodConfig.POST) { sendPostRequest(item, changeConfig); } else { sendPutRequest(item, changeConfig); } } else if (item.isDeleted()) { sendDeleteRequest(item); } } } catch (ClientProtocolException e) { LOGGER.error("Error during restful operation", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } catch (IOException e) { LOGGER.error("Error during restful operation", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } }
From source file:custom.application.login.java
public String http_client(String url) throws ApplicationException { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8"); HttpResponse http_response;/*from w w w . j a v a 2 s . com*/ try { http_response = httpClient.execute(httpget); HeaderIterator iterator = http_response.headerIterator(); while (iterator.hasNext()) { Header next = iterator.nextHeader(); System.out.println(next.getName() + ":" + next.getValue()); } InputStream instream = http_response.getEntity().getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = instream.read(bytes)) != -1) { out.write(bytes, 0, len); } instream.close(); out.close(); return new String(out.toByteArray(), "utf-8"); } catch (ClientProtocolException e) { throw new ApplicationException(e.getMessage(), e); } catch (IOException e) { throw new ApplicationException(e.getMessage(), e); } }
From source file:ss.udapi.sdk.services.HttpServices.java
public ServiceRequest processLogin(ServiceRequest loginReq, String relation, String name) throws Exception { if (loginReq == null) throw new IllegalArgumentException("loginReq must be a valid request"); logger.info("Preparing request for: " + name); CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(loginTimeout).build(); List<RestItem> serviceRestItems = null; ServiceRequest serviceRequest = new ServiceRequest(); RestItem loginDetails = getRestItems(loginReq, name); if (loginDetails == null) { logger.error("Link not found for request " + name); return null; }//from w w w .ja v a 2 s . c o m RestLink link = getLink(loginDetails, relation); if (link == null) { logger.error("Relation not found for relation: " + relation + " for " + name); return null; } CloseableHttpResponse response = null; try { HttpUriRequest httpAction = new HttpPost(link.getHref()); if (compressionEnabled == true) { httpAction.setHeader("Accept-Encoding", "gzip"); } httpAction.setHeader("X-Auth-User", SystemProperties.get("ss.username")); httpAction.setHeader("X-Auth-Key", SystemProperties.get("ss.password")); httpAction.setHeader("Content-Type", "application/json"); // Send the request of to retrieve the Authentication Token and the // list of available services. response = httpClient.execute(httpAction); if (response.getStatusLine().getStatusCode() != 200) { throw new ClientProtocolException("Unexpected response status: " + response.getStatusLine().getStatusCode() + " while retrieving services for: " + name); } if (response.getFirstHeader("X-Auth-Token") == null) throw new ClientProtocolException("Unexpected response: no auth token found"); serviceAuthToken = response.getFirstHeader("X-Auth-Token").getValue(); serviceRequest.setAuthToken(serviceAuthToken); HttpEntity entity = response.getEntity(); String jsonResponse = new String(EntityUtils.toByteArray(entity)); serviceRestItems = JsonHelper.toRestItems(jsonResponse); serviceRequest.setServiceRestItems(serviceRestItems); return serviceRequest; } catch (ClientProtocolException protEx) { logger.error( "Invalid Client Protocol: " + protEx.getMessage() + " while retrieving services for: " + name); throw protEx; } catch (IOException ioEx) { logger.error("Communication error" + ioEx.getCause() + " while retrieving services for: " + name); throw ioEx; } finally { try { httpClient.close(); } catch (IOException ex) { // Can safely be ignored, either the server closed the // connection or we didn't open it so there's nothing to do } } }
From source file:ss.udapi.sdk.services.HttpServices.java
protected String retrieveBody(ServiceRequest request, String relation, String name, String entity) throws Exception { if (request == null) throw new IllegalArgumentException("request object cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(requestTimeout).build(); Exception lastraisedexception = null; // Double check we do have an actual usable service RestItem serviceDetails = getRestItems(request, name); if (serviceDetails == null) { logger.error("No details found for: " + relation + " on " + name); return null; }/*from ww w .j ava 2 s. c o m*/ // The retrieve that service's end-point RestLink link = getLink(serviceDetails, relation); if (link == null) { logger.error("No links found for: " + relation + " on " + name); return null; } String responseBody = ""; try { // Prepare the HTTP request depending on whether it's an echo // (POST), then send the request. if (relation.equals("http://api.sportingsolutions.com/rels/stream/batchecho")) { HttpPost httpPost = new HttpPost(link.getHref()); httpPost.setHeader("X-Auth-Token", request.getAuthToken()); httpPost.setHeader("Content-Type", "application/json"); if (compressionEnabled == true) { httpPost.setHeader("Accept-Encoding", "gzip"); } HttpEntity myEntity = new StringEntity(entity); httpPost.setEntity(myEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 202) { throw new ClientProtocolException("Unexpected response status for echo request: " + httpResponse.getStatusLine().getStatusCode()); } HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { responseBody = new String(EntityUtils.toByteArray(responseEntity)); } // Or anything else (GET), then send the request. } else { HttpGet httpGet = new HttpGet(link.getHref()); httpGet.setHeader("X-Auth-Token", request.getAuthToken()); if (compressionEnabled == true) { httpGet.setHeader("Accept-Encoding", "gzip"); } logger.debug("Sending request for relation:[" + relation + "] name:[" + name + "] to href:[" + link.getHref() + "]"); ResponseHandler<String> responseHandler = getResponseHandler(200); responseBody = httpClient.execute(httpGet, responseHandler); } } catch (ClientProtocolException protEx) { logger.error("Invalid Client Protocol: " + protEx.getMessage() + " while processing : " + name); lastraisedexception = protEx; } catch (IOException ioEx) { logger.error("Communication error: " + ioEx.getMessage() + " while processing : " + name); lastraisedexception = ioEx; } finally { try { httpClient.close(); } catch (IOException ex) { // Can safely be ignored, either the server closed the // connection or we didn't open it so there's nothing to do } } if (lastraisedexception != null) throw lastraisedexception; // Then return the response we got from Sporting Solutions. return responseBody; }
From source file:net.evecom.androidecssp.activity.WelcomeActivity.java
/** * /*from w ww . j ava2s. c o m*/ */ private void getDictSave2SqlData() { new Thread(new Runnable() { @Override public void run() { try { dictResult = connServerForResultPost("jfs/mobile/androidIndex/gitSysDicts", null); } catch (ClientProtocolException e) { Log.e("mars", "" + e.getMessage()); } catch (IOException e) { Log.e("mars", "" + e.getMessage()); } finally { try { putString2Map(dictResult); } catch (JSONException e) { Log.e("mars", "json" + e.getMessage()); } } } }).start(); }
From source file:edu.ucsb.nceas.ezid.EZIDService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * @return byte[] containing the response body *//*from w w w . j a v a 2 s. c o m*/ private byte[] sendRequest(int requestType, String uri, String requestBody) throws EZIDException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EZIDException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpclient.execute(request, handler); } catch (ClientProtocolException e) { throw new EZIDException(e.getMessage()); } catch (IOException e) { throw new EZIDException(e.getMessage()); } return body; }
From source file:net.dahanne.gallery3.client.business.G3Client.java
/** * Send the HTTP request to the gallery/* ww w . j a va 2 s .co m*/ * * @param appendToGalleryUrl * @param nameValuePairs * @param useExistingApiKey * @param requestMethod * @param file * @return the response from the HTTP server * @throws G3GalleryException */ private String sendHttpRequest(String appendToGalleryUrl, List<NameValuePair> nameValuePairs, String requestMethod, File file) throws G3GalleryException { logger.debug("appendToGalleryUrl : {} -- nameValuePairs : {} -- requestMethod : {} -- file : {}", new Object[] { appendToGalleryUrl, nameValuePairs, requestMethod, file != null ? file.getAbsolutePath() : null }); String result; // do we need to login ? do we have the apikey ? if (username != null && existingApiKey == null) { // we are inside a call of getApiKey if (nameValuePairs != null && nameValuePairs.size() != 0) { if (nameValuePairs.get(0).getName().equals("user")) { } else { existingApiKey = getApiKey(); } } else { existingApiKey = getApiKey(); } } try { HttpEntity responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); responseEntity = new BufferedHttpEntity(responseEntity); BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); String line; StringBuilder sb = new StringBuilder(); logger.debug("Beginning reading the response"); try { while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } } finally { reader.close(); } result = sb.toString(); logger.debug("result : {}", result); logger.debug("Ending reading the response"); } catch (ClientProtocolException e) { throw new G3GalleryException(e.getMessage()); } catch (IOException e) { throw new G3GalleryException(e.getMessage()); } logger.debug(""); return result; }
From source file:org.ptlug.ptwifiauth.UserSession.java
public boolean login() { try {// w w w . j a va 2s. c o m int status_def = this.getDefaultUrl(); if (status_def != 1 && status_def != 4) return false; httppost.setEntity(new UrlEncodedFormEntity( PostParametersBuilder.buildLoginParameters(this.username, this.password))); Logger.getInstance().doLog("UserNamePassword", this.username + this.password); httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); last_response = httpclient.execute(httppost); this.debugCookies(); return verifyLogin(); } catch (ClientProtocolException e) { Logger.getInstance().doLog(LogConsts.login_result, "ClientProtocolException " + e.toString()); return false; } catch (IOException e) { Logger.getInstance().doLog(LogConsts.login_result, "IOException " + e.getMessage()); return false; } }