List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:org.oscarehr.fax.admin.ManageFaxes.java
public ActionForward CancelFax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {//from ww w. ja v a 2 s. co m String jobId = request.getParameter("jobId"); if (!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_admin", "w", null)) { throw new SecurityException("missing required security object (_admin)"); } FaxJobDao faxJobDao = SpringUtils.getBean(FaxJobDao.class); FaxConfigDao faxConfigDao = SpringUtils.getBean(FaxConfigDao.class); FaxJob faxJob = faxJobDao.find(Integer.parseInt(jobId)); FaxConfig faxConfig = faxConfigDao.getConfigByNumber(faxJob.getFax_line()); DefaultHttpClient client = new DefaultHttpClient(); String result = "{success:false}"; log.info("TRYING TO CANCEL FAXJOB " + faxJob.getJobId()); if (faxConfig.isActive()) { if (faxJob.getStatus().equals(FaxJob.STATUS.SENT)) { faxJob.setStatus(FaxJob.STATUS.CANCELLED); faxJobDao.merge(faxJob); result = "{success:true}"; } if (faxJob.getJobId() != null) { if (faxJob.getStatus().equals(FaxJob.STATUS.WAITING)) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(faxConfig.getSiteUser(), faxConfig.getPasswd())); HttpPut mPut = new HttpPut(faxConfig.getUrl() + "/fax/" + faxJob.getJobId()); mPut.setHeader("accept", "application/json"); mPut.setHeader("user", faxConfig.getFaxUser()); mPut.setHeader("passwd", faxConfig.getFaxPasswd()); try { HttpResponse httpResponse = client.execute(mPut); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); faxJob.setStatus(FaxJob.STATUS.CANCELLED); faxJobDao.merge(faxJob); } } catch (ClientProtocolException e) { log.error("PROBLEM COMM WITH WEB SERVICE"); } catch (IOException e) { log.error("PROBLEM COMM WITH WEB SERVICE"); } } } } try { JSONObject json = JSONObject.fromObject(result); json.write(response.getWriter()); } catch (IOException e) { log.error(e.getMessage(), e); } return null; }
From source file:nl.nikhef.eduroam.WiFiEduroam.java
private void postData(String username, String password, String csr) throws RuntimeException { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(CONF_HTTP_URL); String android_id = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID); try {/*from w ww .j a v a2s. c om*/ // Add the post data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); nameValuePairs.add(new BasicNameValuePair("csr", csr)); nameValuePairs.add(new BasicNameValuePair("device_id", android_id)); nameValuePairs.add(new BasicNameValuePair("device_serial", android.os.Build.SERIAL)); nameValuePairs.add(new BasicNameValuePair("device_description", android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL + " / " + android.os.Build.PRODUCT)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP POST request synchronously HttpResponse response = httpclient.execute(httppost); if (!response.getStatusLine().toString().endsWith("200 OK")) { updateStatus("HTTP Error: " + response.getStatusLine()); } // Convert input to JSON object BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } String json = builder.toString(); JSONObject obj = new JSONObject(json); if (!obj.getString("status").equals("ok")) { updateStatus("JSON Status Error: " + obj.getString("error")); throw new RuntimeException(obj.getString("error")); } // Grab the information certificate = obj.getString("certificate"); ca = obj.getString("ca"); ca_name = obj.getString("ca_name"); realm = obj.getString("realm"); subject_match = obj.getString("subject_match"); ssid = obj.getString("ssid"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); throw new RuntimeException("Please check your connection!"); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { throw new RuntimeException("JSON: " + e.getMessage()); } }
From source file:org.wso2.carbon.apimgt.keymgt.AMDefaultKeyManagerImpl.java
@Override public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException { String newAccessToken;/* www . ja v a 2 s . c om*/ long validityPeriod; AccessTokenInfo tokenInfo = null; if (tokenRequest == null) { log.warn("No information available to generate Token."); return null; } String tokenEndpoint = configuration.getParameter(APIConstants.TOKEN_URL); //To revoke tokens we should call revoke API deployed in API gateway. String revokeEndpoint = configuration.getParameter(APIConstants.REVOKE_URL); URL keymgtURL = new URL(tokenEndpoint); int keyMgtPort = keymgtURL.getPort(); String keyMgtProtocol = keymgtURL.getProtocol(); // Call the /revoke only if there's a token to be revoked. try { if (tokenRequest.getTokenToRevoke() != null) { URL revokeEndpointURL = new URL(revokeEndpoint); String revokeEndpointProtocol = revokeEndpointURL.getProtocol(); int revokeEndpointPort = revokeEndpointURL.getPort(); HttpClient revokeEPClient = APIKeyMgtUtil.getHttpClient(revokeEndpointPort, revokeEndpointProtocol); HttpPost httpRevokepost = new HttpPost(revokeEndpoint); // Request parameters. List<NameValuePair> revokeParams = new ArrayList<NameValuePair>(3); revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, tokenRequest.getClientId())); revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, tokenRequest.getClientSecret())); revokeParams.add(new BasicNameValuePair("token", tokenRequest.getTokenToRevoke())); //Revoke the Old Access Token httpRevokepost.setEntity(new UrlEncodedFormEntity(revokeParams, "UTF-8")); HttpResponse revokeResponse = revokeEPClient.execute(httpRevokepost); if (revokeResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Token revoke failed : HTTP error code : " + revokeResponse.getStatusLine().getStatusCode()); } else { if (log.isDebugEnabled()) { log.debug( "Successfully submitted revoke request for old application token. HTTP status : 200"); } } } //get default application access token name from config. String applicationScope = APIKeyMgtDataHolder.getApplicationTokenScope(); // When validity time set to a negative value, a token is considered never to expire. if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) { // Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator) tokenRequest.setValidityPeriod(-2); } //Generate New Access Token HttpClient tokenEPClient = APIKeyMgtUtil.getHttpClient(keyMgtPort, keyMgtProtocol); HttpPost httpTokpost = new HttpPost(tokenEndpoint); List<NameValuePair> tokParams = new ArrayList<NameValuePair>(3); tokParams.add(new BasicNameValuePair(OAuth.OAUTH_GRANT_TYPE, GRANT_TYPE_VALUE)); tokParams.add(new BasicNameValuePair(GRANT_TYPE_PARAM_VALIDITY, Long.toString(tokenRequest.getValidityPeriod()))); tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, tokenRequest.getClientId())); tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, tokenRequest.getClientSecret())); StringBuilder builder = new StringBuilder(); builder.append(applicationScope); for (String scope : tokenRequest.getScope()) { builder.append(" " + scope); } tokParams.add(new BasicNameValuePair("scope", builder.toString())); httpTokpost.setEntity(new UrlEncodedFormEntity(tokParams, "UTF-8")); HttpResponse tokResponse = tokenEPClient.execute(httpTokpost); HttpEntity tokEntity = tokResponse.getEntity(); if (tokResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Error occurred while calling token endpoint: HTTP error code : " + tokResponse.getStatusLine().getStatusCode()); } else { tokenInfo = new AccessTokenInfo(); String responseStr = EntityUtils.toString(tokEntity); JSONObject obj = new JSONObject(responseStr); newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).toString(); validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString()); if (obj.has("scope")) { tokenInfo.setScope(((String) obj.get("scope")).split(" ")); } tokenInfo.setAccessToken(newAccessToken); tokenInfo.setValidityPeriod(validityPeriod); } } catch (ClientProtocolException e) { handleException("Error while creating token - Invalid protocol used", e); } catch (UnsupportedEncodingException e) { handleException("Error while preparing request for token/revoke APIs", e); } catch (IOException e) { handleException("Error while creating tokens - " + e.getMessage(), e); } catch (JSONException e) { handleException("Error while parsing response from token api", e); } return tokenInfo; }
From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java
/** * @param context May be null if no notification is needed * @param uri//from w w w. j a v a2 s. co m * @return * @throws AuthenticationException * @throws FileNotFoundException */ private List<DavCalendar> forceGetCalendarsFromUri(Context context, URI uri) throws AuthenticationException, FileNotFoundException { List<DavCalendar> calendars = new ArrayList<DavCalendar>(); Exception exception = null; try { calendars = getCalendarsFromSet(uri); } catch (ClientProtocolException e) { if (context != null) { NotificationsHelper.signalSyncErrors(context, "Caldav sync problem", e.getMessage()); //NotificationsHelper.getCurrentSyncLog().addException(e); } exception = e; } catch (FileNotFoundException e) { if (context != null) { NotificationsHelper.signalSyncErrors(context, "Caldav sync problem", e.getMessage()); //NotificationsHelper.getCurrentSyncLog().addException(e); } throw e; } catch (IOException e) { if (context != null) { NotificationsHelper.signalSyncErrors(context, "Caldav sync problem", e.getMessage()); //NotificationsHelper.getCurrentSyncLog().addException(e); } exception = e; } catch (CaldavProtocolException e) { if (context != null) { NotificationsHelper.signalSyncErrors(context, "Caldav sync problem", e.getMessage()); //NotificationsHelper.getCurrentSyncLog().addException(e); } exception = e; } if (exception != null && BuildConfig.DEBUG) { Log.e(TAG, "Force get calendars from '" + uri.toString() + "' failed " + exception.getClass().getCanonicalName() + ": " + exception.getMessage()); } return calendars; }
From source file:org.commonjava.indy.client.core.IndyClientHttp.java
public void putWithStream(final String path, final InputStream stream, final int... responseCodes) throws IndyClientException { connect();/*from w w w .ja v a2s .c o m*/ final HttpPut put = newRawPut(buildUrl(baseUrl, path)); final CloseableHttpClient client = newClient(); CloseableHttpResponse response = null; try { put.setEntity(new InputStreamEntity(stream)); response = client.execute(put, newContext()); final StatusLine sl = response.getStatusLine(); if (!validResponseCode(sl.getStatusCode(), responseCodes)) { throw new ClientProtocolException(new IndyClientException(sl.getStatusCode(), "Error in response from: %s.\n%s", path, new IndyResponseErrorDetails(response))); } } catch (final ClientProtocolException e) { final Throwable cause = e.getCause(); if (cause != null && (cause instanceof IndyClientException)) { throw (IndyClientException) cause; } throw new IndyClientException("Indy request failed: %s", e, e.getMessage()); } catch (final IOException e) { throw new IndyClientException("Indy request failed: %s", e, e.getMessage()); } finally { cleanupResources(put, response, client); } }
From source file:com.ccxt.whl.DemoApplication.java
/******************************?end***************************************/ @Override/* w w w . j a v a 2 s .c o m*/ public void onCreate() { super.onCreate(); /**********************2014-08-08*************************/ mLocClient = new LocationClient(this); mLocClient.registerLocationListener(myListener); setLocationOption(); startLocate(); //Frontia? Frontia.init(this.getApplicationContext(), "yHMQouqcDqWPR5uEZ7GbW6w4"); //? FrontiaStatistics stat = Frontia.getStatistics(); stat.setReportId("32f5355664"); stat.setAppDistributionChannel("??"); stat.enableExceptionLog(); stat.start(SendStrategyEnum.SET_TIME_INTERVAL, 0, 10, false); //? initImageLoader(this); FrontiaPush mPush = Frontia.getPush(); boolean isWorking = mPush.isPushWorking(); if (isWorking) { Log.d("mpush is runing --> stop"); mPush.stop(); } /**********************2014-08-08*************************/ int pid = android.os.Process.myPid(); String processAppName = getAppName(pid); //?remote serviceif? if (processAppName == null || processAppName.equals("")) { // workaround for baidu location sdk // ?sdk????????application::onCreate // // sdk??? ?pid ?processInfo // processName // application::onCreate service return; } applicationContext = this; instance = this; // ?SDK,?init() Log.d("EMChat Demo initialize EMChat SDK"); EMChat.getInstance().init(applicationContext); // debugmodetrue?sdk?log EMChat.getInstance().setDebugMode(false); // ?EMChatOptions EMChatOptions options = EMChatManager.getInstance().getChatOptions(); // ??????? options.setAcceptInvitationAlways(false); // ???true options.setNotificationEnable(PreferenceUtils.getInstance(applicationContext).getSettingMsgNotification()); // ????true options.setNoticeBySound(PreferenceUtils.getInstance(applicationContext).getSettingMsgSound()); // ?? true options.setNoticedByVibrate(PreferenceUtils.getInstance(applicationContext).getSettingMsgVibrate()); // ?? true options.setUseSpeaker(PreferenceUtils.getInstance(applicationContext).getSettingMsgSpeaker()); //notification?intentintent options.setOnNotificationClickListener(new OnNotificationClickListener() { @Override public Intent onNotificationClick(EMMessage message) { Intent intent = new Intent(applicationContext, ChatActivity.class); ChatType chatType = message.getChatType(); if (chatType == ChatType.Chat) { //??? intent.putExtra("userId", message.getFrom()); intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE); } else { //?? //message.getTo()?id intent.putExtra("groupId", message.getTo()); intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP); } return intent; } }); //connectionlistener??? EMChatManager.getInstance().addConnectionListener(new MyConnectionListener()); //?app??????????? // options.setNotifyText(new OnMessageNotifyListener() { // // @Override // public String onNewMessageNotify(EMMessage message) { // //??message????demo???? // return "?" + message.getFrom() + "????"; // } // // @Override // public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) { // return fromUsersNum + "???" + messageNum + "??"; // } // }); options.setNotifyText(new OnMessageNotifyListener() { @Override public String onNewMessageNotify(EMMessage message) { UserDao dao = new UserDao(applicationContext); User user = dao.getUser(message.getFrom()); //? if (!CommonUtils.isNullOrEmpty(user.toString())) { if (user.getHeaderurl() != null && user.getNick() != null) { Log.d("application local_user_is-pass"); //continue;// String nick = ""; if (CommonUtils.isNullOrEmpty(user.getNick())) { nick = "?"; } nick = "" + user.getNick(); return nick + "????"; } } /***********??????***********/ String nickname_tmp = ""; String headurl_tmp = ""; //???id? if (CommonUtils.isNullOrEmpty(user.getUsername()) || CommonUtils.isNullOrEmpty(user.getHeaderurl()) || CommonUtils.isNullOrEmpty(user.getNick())) { String httpUrl = Constant.BASE_URL + Constant.USER_URL_C + "user=" + message.getFrom(); // httpRequest HttpGet httpRequest = new HttpGet(httpUrl); try { // ?HttpClient HttpClient httpclient = new DefaultHttpClient(); // HttpClient?HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // ? if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // ? String strResult = EntityUtils.toString(httpResponse.getEntity()); if (!CommonUtils.isNullOrEmpty(strResult)) { Map<String, Object> lm = JsonToMapList.getMap(strResult); if (lm.get("status").toString() != null && lm.get("status").toString().equals("yes")) { if (!CommonUtils.isNullOrEmpty(lm.get("result").toString())) { Map<String, Object> result = JsonToMapList .getMap(lm.get("result").toString()); nickname_tmp = result.get("nickname").toString(); headurl_tmp = result.get("headurl").toString(); Log.d("NotifyListener nickname_tmp and headurl_tmp " + nickname_tmp + " " + headurl_tmp); } } } if (!CommonUtils.isNullOrEmpty(nickname_tmp) && !CommonUtils.isNullOrEmpty(headurl_tmp)) { User user_temp = new User(); user_temp.setUsername(message.getFrom()); user_temp.setNick(nickname_tmp); user_temp.setHeaderurl(headurl_tmp); dao.saveContact_m(user_temp); Log.d("NotifyListener saveContact_m have"); } } } catch (ClientProtocolException e) { Log.e("application" + e.getMessage().toString()); } catch (IOException e) { Log.e("application" + e.getMessage().toString()); } catch (Exception e) { Log.e("application" + e.getMessage().toString()); } } return nickname_tmp + "????"; } @Override public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) { return fromUsersNum + "???" + messageNum + "??"; } @Override public String onSetNotificationTitle(EMMessage message) { // TODO Auto-generated method stub UserDao dao = new UserDao(applicationContext); User user = dao.getUser(message.getFrom()); //? if (!CommonUtils.isNullOrEmpty(user.toString())) { if (user.getHeaderurl() != null && user.getNick() != null) { Log.d("application local_user_is-pass"); //continue;// String nick = ""; if (CommonUtils.isNullOrEmpty(user.getNick())) { nick = "?"; } nick = "" + user.getNick(); return nick; } } return "??"; } }); //MobclickAgent.onError(applicationContext); }
From source file:com.myjeeva.digitalocean.impl.DigitalOceanClient.java
private String executeHttpRequest(HttpRequestBase request) throws DigitalOceanException, RequestUnsuccessfulException { String response = ""; try {/*from w w w . j av a2 s . c o m*/ HttpResponse httpResponse = httpClient.execute(request); LOG.debug("HTTP Response Object:: " + httpResponse); response = appendRateLimitValues(evaluateResponse(httpResponse), httpResponse); LOG.debug("Parsed Response:: " + response); } catch (ClientProtocolException cpe) { throw new RequestUnsuccessfulException(cpe.getMessage(), cpe); } catch (IOException ioe) { throw new RequestUnsuccessfulException(ioe.getMessage(), ioe); } finally { request.releaseConnection(); } return response; }
From source file:no.ntnu.idi.socialhitchhiking.facebook.FBConnectionActivity.java
private boolean newUser(String id) { User user = new User("Dummy", id); //"Dummy" and 0.0 are dummy vars. getApp() etc sends the current user's carid Request req = new UserRequest(RequestType.GET_USER, user); UserResponse res = null;/*from w ww . j a v a 2 s .c om*/ try { res = (UserResponse) RequestTask.sendRequest(req, getApp()); System.out.println("Error melding: " + res.getErrorMessage()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block System.out.println("Excecution feil: " + e.getMessage()); e.printStackTrace(); } if (res == null) { return true; } else return false; }
From source file:com.rakesh.d4ty.YTDownloadThread.java
boolean downloadone(String sURL) { boolean rc = false; boolean rc204 = false; boolean rc302 = false; this.iRecursionCount++; // stop recursion try {/*w w w . j av a 2 s. c o m*/ if (sURL.equals("")) return (false); } catch (NullPointerException npe) { return (false); } if (JFCMainClient.getbQuitrequested()) return (false); // try to get information about application shutdown debugoutput("start."); // TODO GUI option for proxy? // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube // using local squid to save download time for tests try { // determine http_proxy environment variable if (!this.getProxy().equals("")) { String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", ""); this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""), Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http"); SchemeRegistry supportedSchemes = new SchemeRegistry(); supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes); // with proxy this.httpclient = new DefaultHttpClient(ccm, params); this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy); this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } else { // without proxy this.httpclient = new DefaultHttpClient(); this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } this.httpget = new HttpGet(getURI(sURL)); if (sURL.toLowerCase().startsWith("https")) this.target = new HttpHost(getHost(sURL), 443, "https"); else this.target = new HttpHost(getHost(sURL), 80, "http"); } catch (Exception e) { debugoutput(e.getMessage()); } debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString())); debugoutput("uri: ".concat(this.httpget.getURI().toString())); debugoutput("host: ".concat(this.target.getHostName())); debugoutput("using proxy: ".concat(this.getProxy())); // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work) /* this.localContext = new BasicHttpContext(); if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context) ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient */ // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again? try { this.response = this.httpclient.execute(this.target, this.httpget, this.localContext); } catch (ClientProtocolException cpe) { debugoutput(cpe.getMessage()); } catch (UnknownHostException uhe) { output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ") .concat(uhe.getMessage())); debugoutput(uhe.getMessage()); } catch (IOException ioe) { debugoutput(ioe.getMessage()); } catch (IllegalStateException ise) { debugoutput(ise.getMessage()); } /* CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN); CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC); CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ; try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( ))); } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute try { debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString())); debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString())); debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString())); } catch (NullPointerException npe) { } */ try { debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString())); //for (int i = 0; i < response.getAllHeaders().length; i++) { // debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue())); //} // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL? if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)")) & !(rc204 = this.response.getStatusLine().toString().toLowerCase() .matches("^(http)(.*)204(.*)")) & !(rc302 = this.response.getStatusLine().toString().toLowerCase() .matches("^(http)(.*)302(.*)"))) { debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL)); output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\"")); return (rc & rc204 & rc302); } if (rc204) { debugoutput("last response code==204 - download: ".concat(this.sNextVideoURL.get(0))); rc = downloadone(this.sNextVideoURL.get(0)); return (rc); } if (rc302) debugoutput( "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString())); } catch (NullPointerException npe) { // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because // response.getStatusLine() == null this.sVideoURL = null; } HttpEntity entity = null; try { entity = this.response.getEntity(); } catch (NullPointerException npe) { } // try to read HTTP response body if (entity != null) { try { if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)")) this.textreader = new BufferedReader(new InputStreamReader(entity.getContent())); else this.binaryreader = new BufferedInputStream(entity.getContent()); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { // test if we got a webpage this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase(); if (this.sContentType.matches("^text/html(.*)")) { savetextdata(); // test if we got the binary content } else if (this.sContentType.matches("video/(.)*")) { if (JFCMainClient.getbNODOWNLOAD()) reportheaderinfo(); else savebinarydata(); } else { // content-type is not video/ rc = false; this.sVideoURL = null; } } catch (IOException ex) { try { throw ex; } catch (IOException e) { e.printStackTrace(); } } catch (RuntimeException ex) { try { throw ex; } catch (Exception e) { e.printStackTrace(); } } } //if (entity != null) this.httpclient.getConnectionManager().shutdown(); debugoutput("done: ".concat(sURL)); try { if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) { debugoutput("cannot download video - URL does not seem to be valid: ".concat(this.sVideoURL)); output(JFCMainClient.isgerman() ? "es gab ein Problem die Video URL zu finden!" : "there was a problem getting the video URL!"); // deutsch output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!" : "consider reporting the URL to author! - ").concat(this.sURL)); rc = false; } else { debugoutput("try to download video from URL: ".concat(this.sVideoURL)); rc = downloadone(this.sVideoURL); } this.sVideoURL = null; } catch (NullPointerException npe) { } return (rc); }