List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:nl.esciencecenter.ptk.web.WebClient.java
public ResponseInputStream doGetInputStream(URI uri) throws WebException { HttpGet getMethod = new HttpGet(uri); try {/*from ww w . j a va 2s . c o m*/ logger.debugPrintf("doGetInputStream()[thread:%d]:'%s'\n", Thread.currentThread().getId(), getMethod.getRequestLine()); HttpResponse response; response = httpClient.execute(getMethod); logger.debugPrintf("--------------- HttpGet Response -------------------------\n"); logger.debugPrintf(" - statusLine: %s\n", response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity == null) { logger.debugPrintf("NULL Entity\n"); getMethod.releaseConnection(); int httpStatus = response.getStatusLine().getStatusCode(); throw new WebException(WebException.Reason.IOEXCEPTION, httpStatus, "Response Entity is NULL"); } // Status must be ok, for the content to be streamed: handleResponseStatus(response, "doGetInputStream:'" + getMethod + "' for:+" + uri + "\n"); // ResponseInputStream responseInps = new ResponseInputStream(this, getMethod, entity); return responseInps; } catch (ClientProtocolException e) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, e.getMessage(), e); } catch (IOException e) { throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e); } }
From source file:com.balakrish.gpstracker.WaypointsListActivity.java
/** * Handle activity menu//from w w w.j av a 2s .co m */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); final long waypointId = waypointsArrayAdapter.getItem((int) info.id).getId(); Cursor tmpCursor; String sql; switch (item.getItemId()) { case 0: // update waypoint in db updateWaypoint(waypointId); return true; case 1: deleteWaypoint(waypointId); return true; case 2: // email waypoint data using default email client String elevationUnit = app.getPreferences().getString("elevation_units", "m"); String elevationUnitLocalized = Utils.getLocalizedElevationUnit(this, elevationUnit); sql = "SELECT * FROM waypoints WHERE _id=" + waypointId + ";"; tmpCursor = app.getDatabase().rawQuery(sql, null); tmpCursor.moveToFirst(); double lat1 = tmpCursor.getDouble(tmpCursor.getColumnIndex("lat")) / 1E6; double lng1 = tmpCursor.getDouble(tmpCursor.getColumnIndex("lng")) / 1E6; String messageBody = getString(R.string.title) + ": " + tmpCursor.getString(tmpCursor.getColumnIndex("title")) + "\n\n" + getString(R.string.lat) + ": " + Utils.formatLat(lat1, 0) + "\n" + getString(R.string.lng) + ": " + Utils.formatLng(lng1, 0) + "\n" + getString(R.string.elevation) + ": " + Utils.formatElevation(tmpCursor.getFloat(tmpCursor.getColumnIndex("elevation")), elevationUnit) + elevationUnitLocalized + "\n\n" + "http://maps.google.com/?ll=" + lat1 + "," + lng1 + "&z=10"; tmpCursor.close(); final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.email_subject_waypoint)); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, messageBody); this.startActivity(Intent.createChooser(emailIntent, getString(R.string.sending_email))); return true; case 3: this.showOnMap(waypointId); return true; case 4: // TODO: use a thread for online sync // sync one waypoint data with remote server // create temp waypoint from current record Waypoint wp = Waypoints.get(app.getDatabase(), waypointId); try { // preparing query string for calling web service String lat = Location.convert(wp.getLocation().getLatitude(), 0); String lng = Location.convert(wp.getLocation().getLongitude(), 0); String title = URLEncoder.encode(wp.getTitle()); String userName = app.getPreferences().getString("user_name", ""); String userPassword = app.getPreferences().getString("user_password", ""); String sessionValue = userName + "@" + Utils.md5("aripuca_session" + userPassword); if (userName.equals("") || userPassword.equals("")) { Toast.makeText(WaypointsListActivity.this, R.string.username_or_password_required, Toast.LENGTH_SHORT).show(); return false; } String queryString = "?do=ajax_map_handler&aripuca_session=" + sessionValue + "&action=add_point&lat=" + lat + "&lng=" + lng + "&z=16&n=" + title + "&d=AndroidSync"; // http connection HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet( app.getPreferences().getString("online_sync_url", "http://tracker.aripuca.com") + queryString); HttpResponse response = httpClient.execute(httpGet, localContext); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); response.getEntity().writeTo(outstream); // parsing JSON return JSONObject jsonObject = new JSONObject(outstream.toString()); Toast.makeText(WaypointsListActivity.this, jsonObject.getString("message").toString(), Toast.LENGTH_SHORT).show(); } catch (ClientProtocolException e) { Toast.makeText(WaypointsListActivity.this, "ClientProtocolException: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(WaypointsListActivity.this, "IOException " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } catch (JSONException e) { Toast.makeText(WaypointsListActivity.this, "JSONException " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } return true; default: return super.onContextItemSelected(item); } }
From source file:nl.esciencecenter.ptk.web.WebClient.java
public boolean connect() throws WebException { httpClient = new DefaultHttpClient(); if (config.isMultiThreaded()) { ClientConnectionManager connectionManager = new PoolingClientConnectionManager(); httpClient = new DefaultHttpClient(connectionManager); }/*from w w w . j a va2 s . co m*/ try { if (config.isHTTPS()) { if (this.certStore == null) { logger.warnPrintf("Warning: HTTPS procotol with no CertificateStore\n"); } else { initSSL(this.certStore, true); } } if ((config.getUseBasicAuthentication()) && (config.hasPassword() == false) && (this.jsessionID == null) && (this.hasUI())) { String user = getUsername(); SecretHolder secret = new SecretHolder(); boolean result = uiPromptPassfield( "Password for user:" + user + "@" + config.getHostname() + ":" + config.getPort(), secret); if (result == false) { return false; // cancelled. } this.config.password = secret.get(); } // httpClient.getCredentialsProvider().setCredentials(new // AuthScope(config.getHostname(), config.getPort()), // new UsernamePasswordCredentials(config.getUsername(), new // String(config.getPasswordChars()))); if (config.useJSession()) { initJSession(false); return true; } else { // check service URI. HttpGet httpget = new HttpGet(serviceUri); logger.debugPrintf("connect(): Executing request: %s\n", httpget.getRequestLine()); HttpResponse response = httpClient.execute(httpget); logger.debugPrintf("connect(): ------------ Response ----------\n"); StringHolder textH = new StringHolder(); this.lastHttpStatus = handleStringResponse("connect()" + serviceUri, response, textH, null); return true; } } catch (ClientProtocolException e) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, e.getMessage(), e); } catch (javax.net.ssl.SSLPeerUnverifiedException e) { throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Verification Error:" + e.getMessage(), e); } catch (WebException e) { throw (e); // pass } catch (IOException e) { throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e); } finally { // check connected state... } }
From source file:Default.YTDownloadThread.java
public boolean downloadOne(String url) throws IOException { boolean rc = false; boolean rc204 = false; boolean rc302 = false; this.recursionCount++; // stop recursion try {/* w ww . ja v a 2 s . co m*/ if (url.equals("")) { return (false); } } catch (NullPointerException npe) { return (false); } // if (JFCMainClient.getQuitRequested()) { // return(false); // try to get information about application shutdown // } outputDebugMessage("start."); // TODO GUI option for proxy? // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube // using local squid to save download time for tests try { this.request = new HttpGet(url); this.request.setConfig(this.config); this.httpClient = HttpClients.createDefault(); } catch (Exception e) { outputDebugMessage(e.getMessage()); } outputDebugMessage("executing request: ".concat(this.request.getRequestLine().toString())); outputDebugMessage("uri: ".concat(this.request.getURI().toString())); outputDebugMessage("using proxy: ".concat(this.getProxy())); try { this.response = this.httpClient.execute(this.request); } catch (ClientProtocolException cpe) { outputDebugMessage(cpe.getMessage()); } catch (UnknownHostException uhe) { output(("error connecting to: ").concat(uhe.getMessage())); outputDebugMessage(uhe.getMessage()); } catch (IOException ioe) { outputDebugMessage(ioe.getMessage()); } catch (IllegalStateException ise) { outputDebugMessage(ise.getMessage()); } try { outputDebugMessage("HTTP response status line:".concat(this.response.getStatusLine().toString())); // 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(.*)"))) { outputDebugMessage(this.response.getStatusLine().toString().concat(" ").concat(url)); output(this.response.getStatusLine().toString().concat(" \"").concat(this.title).concat("\"")); return (rc & rc204 & rc302); } if (rc204) { rc = downloadOne(this.nextVideoUrl.get(0).getUrl()); return (rc); } if (rc302) { outputDebugMessage( "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.videoUrl = null; } HttpEntity entity = null; try { entity = this.response.getEntity(); } catch (NullPointerException npe) { //TODO catch must not be empty } // 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.contentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase(); if (this.contentType.matches("^text/html(.*)")) { rc = saveTextData(); // test if we got the binary content } else if (this.contentType.matches("(audio|video)/(.*)|application/octet-stream")) { // add audio stream URL if necessary if (this.recursionCount == 1) { outputDebugMessage(("last response code==true - download: ") .concat(this.nextVideoUrl.get(0).getYoutubeId())); if (this.nextVideoUrl.get(0).getAudioStreamUrl().equals("")) { outputDebugMessage("download audio stream? no"); } else { // FIXME audio stream has no filename if we add the direct URL to the GUI url list - we should add YTURL objects, not Strings! outputDebugMessage("download audio stream? yes - " .concat(this.nextVideoUrl.get(0).getAudioStreamUrl())); this.youtubeUrl.setTitle(this.getTitle()); //JFCMainClient.addYoutubeUrlToList(this.nextVideoUrl.get(0).getAudioStreamUrl(),this.getTitle(),"AUDIO"); } } // if (JFCMainClient.getNoDownload()) // reportHeaderInfo(); // else saveBinaryData(); } else { // content-type is not video/ rc = false; this.videoUrl = 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.close(); outputDebugMessage("done: ".concat(url)); if (this.videoUrl == null) { this.videoUrl = ""; // to prevent NPE } if (this.videoUrl.matches(URL_REGEX)) { // enter recursion - download video resource outputDebugMessage("try to download video from URL: ".concat(this.videoUrl)); rc = downloadOne(this.videoUrl); } else { // no more recursion - html source hase been read // rc==false if video could not downloaded because of some error (like wrong protocol or country restriction) if (!rc) { outputDebugMessage("cannot download video - URL does not seem to be valid or could not be found: " .concat(this.url)); output("there was a problem getting the video URL! perhaps not allowed in your country?!"); output(("consider reporting the URL to author! - ").concat(this.url)); this.videoUrl = null; } } this.videoUrl = null; return (rc); }
From source file:nl.esciencecenter.ptk.web.WebClient.java
/** * Execute Put or Post method and handle the (optional) String response. * Returns actual HTTP Status. Method does not do any (http) response status * handling. If the Put method succeeded but the HTTP status != 200 then * this value is returned and no Exception is thrown. * /*from w w w .j ava 2 s . co m*/ * @param putOrPostmethod * - HttpPut or HttpPost method to execute * @param responseTextHolder * - Optional StringHolder for the Response: Put and Post might * nor return any response. * @param contentTypeHolder * - Optional StringHolder for the contentType (mimeType). * * @return actual HTTP Status as returned by server. * @throws WebException * if a communication error occurred. */ protected int executeAuthenticatedPut(HttpRequestBase putOrPostmethod, StringHolder responseTextHolder, StringHolder contentTypeHolder) throws WebException { if (this.httpClient == null) { throw new NullPointerException("HTTP Client not properly initialized: httpClient==null"); } logger.debugPrintf("executePutOrPost():'%s'\n", putOrPostmethod.getRequestLine()); boolean isPut = (putOrPostmethod instanceof HttpPut); boolean isPost = (putOrPostmethod instanceof HttpPost); if ((isPut == false) && (isPost == false)) { throw new IllegalArgumentException( "Method class must be either HttpPut or HttpPost. Class=" + putOrPostmethod.getClass()); } String actualUser; try { HttpResponse response; if (config.getUseBasicAuthentication()) { actualUser = config.getUsername(); String passwdStr = new String(config.getPasswordChars()); logger.debugPrintf("Using basic authentication, user=%s\n", actualUser); Header authHeader = new BasicHeader("Authorization", "Basic " + (StringUtil.base64Encode((actualUser + ":" + passwdStr).getBytes()))); putOrPostmethod.addHeader(authHeader); } response = httpClient.execute(putOrPostmethod); int status = handleStringResponse("executePutOrPost():" + putOrPostmethod.getRequestLine(), response, responseTextHolder, contentTypeHolder); this.lastHttpStatus = status; return status; } catch (ClientProtocolException e) { if ((config.getPort() == 443) && config.isHTTP()) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTP Protocol error: Trying to speak plain http to (SSL) port 443?\n" + e.getMessage(), e); } else if (config.isHTTPS()) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTPS Protocol error:" + e.getMessage(), e); } else { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTP Protocol error:" + e.getMessage(), e); } } catch (javax.net.ssl.SSLPeerUnverifiedException e) { throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n" + e.getMessage(), e); } catch (javax.net.ssl.SSLException e) { // Super class throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n" + e.getMessage(), e); } catch (java.net.NoRouteToHostException e) { throw new WebException(WebException.Reason.NO_ROUTE_TO_HOST_EXCEPTION, "No route to host: Server could be down or unreachable.\n" + e.getMessage(), e); } catch (IOException e) { throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e); } }
From source file:com.frochr123.fabqr.gui.FabQRUploadDialog.java
private void btnPublishActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnPublishActionPerformed {//GEN-HEADEREND:event_btnPublishActionPerformed // Disable all GUI elements and set loading status handleGUIElements(false, true);/* ww w . j a v a 2 s .c o m*/ // Start new thread to prepare and upload data new Thread(new Runnable() { public void run() { try { // Check for valid situation, otherwise abort if (MainView.getInstance() == null || VisicutModel.getInstance() == null || VisicutModel.getInstance().getPlfFile() == null || PreferencesManager.getInstance() == null || PreferencesManager.getInstance().getPreferences() == null || !FabQRFunctions.isFabqrActive() || FabQRFunctions.getFabqrPrivateURL() == null || FabQRFunctions.getFabqrPrivateURL().isEmpty()) { throw new Exception(bundle.getString("ERROR_CRITICAL")); } // Texts String name = txtName.getText(); String email = txtEmail.getText(); String projectName = txtProjectName.getText(); name = ((name == null) ? "" : name.trim()); email = ((email == null) ? "" : email.trim()); projectName = ((projectName == null) ? "" : projectName.trim()); // Check valid project name if (projectName.isEmpty()) { throw new Exception(bundle.getString("ERROR_EMPTY_PROJECT_NAME")); } if (projectName.length() < 3) { throw new Exception(bundle.getString("ERROR_TOO_SHORT_PROJECT_NAME")); } // Get license index, index -1 = error, index 0 = requires no name / mail, index > 0 requires name and email int licenseIndex = cmbbxLicense.getSelectedIndex(); // Check valid license if (licenseIndex < 0) { throw new Exception(bundle.getString("ERROR_INVALID_LICENSE")); } // Check for valid name and email, needed for these licenses else if (licenseIndex > 0) { if (name.isEmpty()) { throw new Exception(bundle.getString("ERROR_LICENSE_NEEDS_NAME")); } if (email.isEmpty()) { throw new Exception(bundle.getString("ERROR_LICENSE_NEEDS_EMAIL")); } } // For these cases email must be checked if (licenseIndex > 0 || !email.isEmpty()) { // Simple and inaccurate check for valid email with regex Pattern emailPattern = Pattern.compile("^.+@.+\\..+$"); if (!emailPattern.matcher(email).find()) { throw new Exception(bundle.getString("ERROR_INVALID_EMAIL")); } } // Build string for selected tools String tools = "Laser cutter"; if (cbPCBSoldering.isSelected()) { tools = tools + ",PCB / Soldering"; } if (cb3DPrinter.isSelected()) { tools = tools + ",3D printer"; } if (cbCNCRouter.isSelected()) { tools = tools + ",CNC router"; } if (cbArduino.isSelected()) { tools = tools + ",Arduino"; } if (cbRaspberryPi.isSelected()) { tools = tools + ",Raspberry Pi"; } // Check valid description String description = txtDescription.getText(); description = ((description == null) ? "" : description.trim()); if (description.isEmpty()) { throw new Exception(bundle.getString("ERROR_EMPTY_DESCRIPTION")); } // Images, real image is allowed to be null, scheme image must not be null BufferedImage imageReal = latestFullCameraImage; BufferedImage imageScheme = PreviewImageExport.generateImage( RefreshProjectorThread.getProjectorWidth(), RefreshProjectorThread.getProjectorHeight(), true); if (imageScheme == null) { throw new Exception(bundle.getString("ERROR_EMPTY_SCHEME_IMAGE")); } // Get PLF data PlfFile plfFile = VisicutModel.getInstance().getPlfFile(); // Check PLF data if (plfFile == null) { throw new Exception(bundle.getString("ERROR_INVALID_PLF_DATA")); } // Get internal data: lasercutter name String lasercutterName = ""; if (VisicutModel.getInstance().getSelectedLaserDevice() != null && VisicutModel.getInstance().getSelectedLaserDevice().getLaserCutter() != null) { lasercutterName = VisicutModel.getInstance().getSelectedLaserDevice().getLaserCutter() .getModelName(); lasercutterName = ((lasercutterName == null) ? "" : lasercutterName.trim()); } // Check lasercutter name if (lasercutterName.isEmpty()) { throw new Exception(bundle.getString("ERROR_EMPTY_LASERCUTTER_NAME")); } // Get internal data: lasercutter material string String lasercutterMaterial = ""; if (VisicutModel.getInstance().getMaterial() != null) { String lasercutterMaterialName = VisicutModel.getInstance().getMaterial().getName(); lasercutterMaterialName = ((lasercutterMaterialName == null) ? "" : lasercutterMaterialName.trim()); // Check material name if (lasercutterMaterialName.isEmpty()) { throw new Exception(bundle.getString("ERROR_EMPTY_MATERIAL_NAME")); } float lasercutterMaterialThickness = VisicutModel.getInstance().getMaterialThickness(); lasercutterMaterial = lasercutterMaterialName + ", " + new Float(lasercutterMaterialThickness).toString() + " mm"; } // Get internal data: Location, FabLab name String location = PreferencesManager.getInstance().getPreferences().getLabName(); if (location == null || location.isEmpty()) { throw new Exception(bundle.getString("ERROR_INVALID_FABLAB_NAME")); } // Upload data FabQRFunctions.uploadFabQRProject(name, email, projectName, licenseIndex, tools, description, location, imageReal, imageScheme, plfFile, lasercutterName, lasercutterMaterial); // On success show suscess message and disable loading icon showStatus(bundle.getString("SUCCESS_MESSAGE")); lblStatus.setIcon(null); // On success enable cancel button again to close dialog btnClose.setEnabled(true); } catch (ClientProtocolException e) { // Enable all GUI elements and disable loading status handleGUIElements(true, true); // Show error message if (e.getCause() != null && e.getCause().getMessage() != null && !e.getCause().getMessage().isEmpty()) { showStatus("HTTP exception: " + e.getCause().getMessage()); } else { showStatus(e.getMessage()); } } catch (Exception e) { // Enable all GUI elements and disable loading status handleGUIElements(true, true); // Show error message showStatus(e.getMessage()); } } }).start(); }
From source file:com.ccxt.whl.activity.MainActivity.java
/** * MainActivity ?//from w w w.j ava2 s. c om * @param toChatUsername ?id * @param is_fran ?? : true?false */ public void get_add_info(final String toChatUsername, final boolean is_fran) { new Thread(new Runnable() { public void run() { UserDao dao = new UserDao(MainActivity.this); String httpUrl = Constant.BASE_URL + Constant.USER_URL_C + "user=" + toChatUsername; // 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("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(toChatUsername); user_temp.setNick(nickname_tmp); user_temp.setHeaderurl(headurl_tmp); if (is_fran) { dao.saveContact(user_temp); } else { dao.saveContact_m(user_temp); } //dao.saveContact(user_temp); Log.d("saveContact have"); } } } catch (ClientProtocolException e) { Log.e(e.getMessage().toString()); } catch (IOException e) { Log.e(e.getMessage().toString()); } catch (Exception e) { Log.e(e.getMessage().toString()); } // TODO Auto-generated method stub /****************************************??****************************************** / //final String toChatUsername = intent.getStringExtra("from"); final UserDao userdao = new UserDao(MainActivity.this); final User local_user = userdao.getUser(toChatUsername); //? if(CommonUtils.isNullOrEmpty(local_user.toString())){ RequestParams params = new RequestParams(); params.add("user", toChatUsername); HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) { // TODO Auto-generated method stub Log.d("rawJsonResponse", rawJsonResponse); if(CommonUtils.isNullOrEmpty(rawJsonResponse)){ nickname = ""; headurl = ""; } Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse); if(lm.get("status").toString() != null && lm.get("status").toString().equals("yes")){ if(!CommonUtils.isNullOrEmpty(lm.get("result"))){ Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString()); nickname = result.get("nickname").toString(); headurl = result.get("headurl").toString(); local_user.setUsername(toChatUsername); local_user.setNick(nickname); local_user.setHeaderurl(headurl); if(is_fran){ userdao.saveContact(local_user); }else{ userdao.saveContact_m(local_user); } /*********************0902********************** / if (currentTabIndex != CHATHISTORYFRAGMENT) { FragmentTransaction trx = getSupportFragmentManager().beginTransaction(); trx.hide(fragments[currentTabIndex]); if (!fragments[CHATHISTORYFRAGMENT].isAdded()) { trx.add(R.id.fragment_container, fragments[CHATHISTORYFRAGMENT]); } trx.show(fragments[CHATHISTORYFRAGMENT]).commit(); } /*****************0901****************** / //if (currentTabIndex == 2) { // ?????? if (chatHistoryFragment != null) { chatHistoryFragment.refresh(); } //} /******************0901end***************** / }else{ nickname = ""; headurl = ""; } }else{ nickname = ""; headurl = ""; } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) { // TODO Auto-generated method stub nickname = ""; headurl = ""; } @Override protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable { // TODO Auto-generated method stub return null; } }); }else{//?? Log.d("local_user", ""+local_user.toString()); nickname = ""; headurl = ""; } /****************************************??*****************************************/ } }).start(); }
From source file:com.ccxt.whl.activity.MainActivity_0903.java
/** * loginactivity??db/*from ww w . j a va 2 s. co m*/ */ private void loadcontact() { // TODO Auto-generated method stub new Thread(new Runnable() { public void run() { Map<String, User> userlists = new HashMap<String, User>(); userlists = DemoApplication.getInstance().getContactList(); if (userlists.size() < 2) { return; } final UserDao dao = new UserDao(MainActivity_0903.this); List<User> users = new ArrayList<User>(userlists.values()); //if(users.l) for (final User user : users) { if (user.getUsername().equals(Constant.NEW_FRIENDS_USERNAME) || user.getUsername().equals(Constant.GROUP_USERNAME)) { dao.saveContact(user); Log.d(TAG, "NEW_FRIENDS_USERNAME-pass"); continue;// } User local_user_is = dao.getUser(user.getUsername()); //? if (!CommonUtils.isNullOrEmpty(local_user_is.toString())) { if (local_user_is.getHeaderurl() != null && local_user_is.getNick() != null && local_user_is.getIs_stranger().equals("2")) { Log.d(TAG, "local_user_is-pass"); continue;// } } //???id? if (CommonUtils.isNullOrEmpty(user.getUsername()) || CommonUtils.isNullOrEmpty(user.getHeaderurl()) || CommonUtils.isNullOrEmpty(user.getNick())) { String httpUrl = Constant.BASE_URL + Constant.USER_URL_C + "user=" + user.getUsername(); // 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(TAG, "nickname_tmp and headurl_tmp " + nickname_tmp + " " + headurl_tmp); /*User user_temp = new User(); user_temp.setUsername(user.getUsername()); user_temp.setNick(nickname_tmp); user_temp.setHeaderurl(headurl_tmp); dao.saveContact(user_temp);*/ } } } if (!CommonUtils.isNullOrEmpty(nickname_tmp) && !CommonUtils.isNullOrEmpty(headurl_tmp)) { User user_temp = new User(); user_temp.setUsername(user.getUsername()); user_temp.setNick(nickname_tmp); user_temp.setHeaderurl(headurl_tmp); dao.saveContact(user_temp); Log.d(TAG, "saveContact have"); } /*else{ User local_user = dao.getUser(user.getUsername()); //? if(!CommonUtils.isNullOrEmpty(local_user.toString())){ if(!CommonUtils.isNullOrEmpty(local_user.getHeaderurl()) &&!CommonUtils.isNullOrEmpty(local_user.getNick())){ //local_user } }else{//?? (??) if (user.getUsername().equals(Constant.NEW_FRIENDS_USERNAME) || user.getUsername().equals(Constant.GROUP_USERNAME)) { //user.setHeader(""); dao.saveContact(user); }else{ user.setNick(""); dao.saveContact(user); Log.d(TAG,"saveContact not have"); } } }*/ } } catch (ClientProtocolException e) { Log.d(TAG, e.getMessage().toString()); } catch (IOException e) { Log.d(TAG, e.getMessage().toString()); } catch (Exception e) { Log.d(TAG, e.getMessage().toString()); } /*RequestParams params = new RequestParams(); params.add("user", user.getUsername()); HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) { // TODO Auto-generated method stub Log.d("rawJsonResponse", rawJsonResponse); if(!CommonUtils.isNullOrEmpty(rawJsonResponse)){ Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse); if(lm.get("status").toString() != null && lm.get("status").toString().equals("yes")){ if(!CommonUtils.isNullOrEmpty(lm.get("result"))){ Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString()); nickname_tmp = result.get("nickname").toString(); headurl_tmp = result.get("headurl").toString(); Log.d(TAG,"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(user.getUsername()); user_temp.setNick(nickname); user_temp.setHeaderurl(headurl); dao.saveContact(user_temp); Log.d(TAG,"saveContact have"); }else{ User local_user = dao.getUser(user.getUsername()); //? if(!CommonUtils.isNullOrEmpty(local_user.toString())){ if(!CommonUtils.isNullOrEmpty(local_user.getHeaderurl()) &&!CommonUtils.isNullOrEmpty(local_user.getNick())){ //local_user } }else{//?? user.setNick(""); dao.saveContact(user); Log.d(TAG,"saveContact not have"); } } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) { // TODO Auto-generated method stub } @Override protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable { // TODO Auto-generated method stub return null; } });*/ } } /**???? User local_user = dao.getUser(user.getUsername()); //? if(!CommonUtils.isNullOrEmpty(local_user.toString())){ if(local_user.getHeaderurl()!=null&&local_user.getNick()!=null){ } }*/ } //dao.saveContactList(users); }).start(); }
From source file:fm.last.android.player.StreamProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;/* w w w . j a v a 2 s. c o m*/ } Log.d(LOG_TAG, "processing"); String url = request.getRequestLine().getUri(); DefaultHttpClient seed = new DefaultHttpClient(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(), registry); DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams()); HttpGet method = new HttpGet(url); for (Header h : request.getAllHeaders()) { method.addHeader(h); } HttpResponse realResponse = null; try { Log.d(LOG_TAG, "starting download"); realResponse = http.execute(method); Log.d(LOG_TAG, "downloaded"); } catch (ClientProtocolException e) { Log.e(LOG_TAG, "Error downloading", e); } catch (IOException e) { Log.e(LOG_TAG, "Error downloading", e); } if (realResponse == null) { return; } if (!isRunning) return; Log.d(LOG_TAG, "downloading..."); InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse response = new BasicHttpResponse(line); response.setHeaders(realResponse.getAllHeaders()); Log.d(LOG_TAG, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(response.getStatusLine().toString()); httpString.append("\n"); for (Header h : response.getAllHeaders()) { httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n"); } httpString.append("\n"); Log.d(LOG_TAG, "headers done"); try { byte[] buffer = httpString.toString().getBytes(); int readBytes; Log.d(LOG_TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start streaming content. byte[] buff = new byte[8192]; while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { mgr.shutdown(); client.close(); Log.d(LOG_TAG, "streaming complete"); } }
From source file:org.meerkat.services.WebApp.java
/** * checkWebAppStatus/*from ww w. j av a 2 s. c o m*/ * * @return WebAppResponse */ public WebAppResponse checkWebAppStatus() { // Set the response at this point to empty in case of no response at all setCurrentResponse(""); int statusCode = 0; // Create an instance of HttpClient. MeerkatHttpClient meerkatClient = new MeerkatHttpClient(); DefaultHttpClient httpclient = meerkatClient.getHttpClient(); WebAppResponse response = new WebAppResponse(); response.setResponseAppType(); // Create a method instance. HttpGet httpget = new HttpGet(url); // Measure the response time Counter c = new Counter(); c.startCounter(); // Execute the method. HttpResponse httpresponse = null; try { httpresponse = httpclient.execute(httpget); // Set the http status statusCode = httpresponse.getStatusLine().getStatusCode(); } catch (ClientProtocolException e) { log.error("Client Protocol Exception", e); response.setHttpStatus(0); response.setHttpTextResponse(e.toString()); setCurrentResponse(e.toString()); response.setContainsWebAppExpectedString(false); c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); httpclient.getConnectionManager().shutdown(); return response; } catch (IOException e) { log.error("IOException - " + e.getMessage()); response.setHttpStatus(0); response.setHttpTextResponse(e.toString()); setCurrentResponse(e.toString()); response.setContainsWebAppExpectedString(false); c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); httpclient.getConnectionManager().shutdown(); return response; } response.setHttpStatus(statusCode); // Consume the response body try { httpresponse.getEntity().getContent().toString(); } catch (IllegalStateException e) { log.error("IllegalStateException", e); } catch (IOException e) { log.error("IOException", e); } // Get the response BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent())); } catch (IllegalStateException e1) { log.error("IllegalStateException in http buffer", e1); } catch (IOException e1) { log.error("IOException in http buffer", e1); } String readLine; String responseBody = ""; try { while (((readLine = br.readLine()) != null)) { responseBody += "\n" + readLine; } } catch (IOException e) { log.error("IOException in http response", e); } try { br.close(); } catch (IOException e) { log.error("Closing BufferedReader", e); } response.setHttpTextResponse(responseBody); setCurrentResponse(responseBody); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); if (statusCode != HttpStatus.SC_OK) { log.warn("Httpstatus code: " + statusCode + " | Method failed: " + httpresponse.getStatusLine()); } // Check if the response contains the expectedString if (getCurrentResponse().contains(expectedString)) { response.setContainsWebAppExpectedString(true); } // Stop the counter c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); return response; }