List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:eu.lod2.ExportSelector3.java
public static List<String> request_graphs() throws Exception { List<String> result = null; HttpClient httpclient = new DefaultHttpClient(); try {/* w w w . j a va 2s .c o m*/ String prefixurl = "http://localhost:8080/lod2webapi/graphs"; HttpGet httpget = new HttpGet(prefixurl); httpget.addHeader("accept", "application/json"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); result = parse_graph_api_result(responseBody); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return result; }
From source file:com.da.img.SoStroyInfoList.java
protected void executeURL(String p_page, String p_author_id, String p_gnum) throws IOException, ClientProtocolException, URISyntaxException { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w ww . jav a2s . c om*/ HttpGet httpget = executeLogin(httpclient); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = ""; // /bank/story_mn.php?p_userid=bluesman&p_snum=201&p_num=35788 // String strUrl = // "http://story.soraspace.info/bank/story_mn.php?p_userid=bluesman&p_snum=201&p_num=35821"; // : // http://photo.soraspace.info/album/theme/pic_list.php?p_anum=173&p_ix=3&p_gnum=351 // http://photo.soraspace.info/album/theme/pic_list.php?p_page=1&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt= // http://photo.soraspace.info/album/theme/pic_list.php?p_page=2&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt= // http://photo.soraspace.info/album/theme/pic_list.php?p_page=3&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt= // http://photo.soraspace.info/album/theme/pic_list.php?p_page=3&p_sort=D&p_anum=351&p_gnum=351&p_soption=&p_stxt= // p_anum=244&p_ix=1 ? // p_anum=281&p_ix=2 // p_anum=173&p_ix=3 ? // p_gnum= 351 : mom , 481: lip , 352: hip, // 354:ga,353:leg,442:pussy, // /honor/author_board_list.php?p_userid=bluesman&p_soption=storyname&p_stxt=? // String p_gnum ="481"; List<ImageVo> lst = null; int max_page = 10000; int init_page = 1; if (!"".equals(StringUtils.stripToEmpty(p_page))) { init_page = Integer.parseInt(p_page); } // init_page = 17; SAVE_DIR = STORY_DIR + "/story/" + p_author_id; //p_author_id ="we"; for (int i = init_page; i < max_page; i++) { lst = getBoardList(httpclient, httpget, responseHandler, p_gnum, String.valueOf(i), p_author_id); System.out.println("Story Size: " + lst.size()); if (lst.size() < 1) { break; } } } catch (Exception ex) { ex.printStackTrace(System.out); System.out.println("ERROR: " + ex.getLocalizedMessage()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.sociotech.communitymashup.source.readability.apiwrapper.ReadabilityAPIWrapper.java
@SuppressWarnings("unused") private String doPost(String url, Map<String, String> parameterMap) { String result = null;/*from w w w . ja va 2 s . c om*/ HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); // add all post parameter for (String key : parameterMap.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, parameterMap.get(key))); } ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); result = httpClient.execute(post, responseHandler); } catch (Exception e) { // do nothing } finally { // client is no longer needed httpClient.getConnectionManager().shutdown(); } return result; }
From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java
@Override protected void onHandleIntent(Intent intent) { // initialize // extract details Server server = intent.getParcelableExtra("server"); String directory = intent.getStringExtra("directory"); String filename = intent.getStringExtra("filename"); // get the json parser from the application JsonParser jsonParser = new JsonParser(); // start the ball rolling... final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); final NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setTicker(String.format(getString(R.string.notif_ticker), filename)) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large)) .setSmallIcon(R.drawable.ic_stat_notif_small) .setContentTitle(String.format(getString(R.string.notif_title), filename)) .setContentText(getString(R.string.notif_content_init)) // to avoid NPE on android 2.x where content intent is required // set an empty content intent .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true); // notify user that upload is starting mgr.notify(NOTIFICATION_ID, builder.build()); // reset ticker for any subsequent notifications builder.setTicker(null);//from ww w . ja v a 2 s. c o m AbstractHttpClient client = CustomHTTPClient.getHttpClient(); // enable digest authentication if (server.getUsername() != null && !server.getUsername().equals("")) { Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword()); client.getCredentialsProvider().setCredentials( new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials); } final File file = new File(directory, filename); final long length = file.length(); try { CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { // calculate percentage //System.out.println("transferred: " + num); int progress = (int) ((num * 100) / length); builder.setContentText(String.format(getString(R.string.notif_content), progress)); mgr.notify(NOTIFICATION_ID, builder.build()); } }); multipart.addPart(file.getName(), new FileBody(file)); HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content"); httpRequest.setEntity(multipart); HttpResponse serverResponse = client.execute(httpRequest); BasicResponseHandler handler = new BasicResponseHandler(); JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject(); if (!reply.has("outcome")) { throw new RuntimeException(getString(R.string.invalid_response)); } else { // remove the 'upload in-progress' notification mgr.cancel(NOTIFICATION_ID); String outcome = reply.get("outcome").getAsString(); if (outcome.equals("success")) { String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString(); Intent resultIntent = new Intent(this, UploadCompletedActivity.class); // populate it resultIntent.putExtra("server", server); resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE); resultIntent.putExtra("filename", filename); resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // the notification id for the 'completed upload' notification // each completed upload will have a different id int notifCompletedID = (int) System.currentTimeMillis(); builder.setContentTitle(getString(R.string.notif_title_uploaded)) .setContentText(String.format(getString(R.string.notif_content_uploaded), filename)) .setContentIntent( // we set the (2nd param request code to completedID) // see http://tinyurl.com/kkcedju PendingIntent.getActivity(this, notifCompletedID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true).setOngoing(false); mgr.notify(notifCompletedID, builder.build()); } else { JsonElement elem = reply.get("failure-description"); if (elem.isJsonPrimitive()) { throw new RuntimeException(elem.getAsString()); } else if (elem.isJsonObject()) throw new RuntimeException( elem.getAsJsonObject().get("domain-failure-description").getAsString()); } } } catch (Exception e) { builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false); mgr.notify(NOTIFICATION_ID, builder.build()); } }
From source file:com.harlap.test.http.MockHttpServerBehaviour.java
@Test public void testShouldHandleMultipleRequests() throws ClientProtocolException, IOException { // Given a mock server configured to respond to a POST / with data // "Hello World" with an ID // And configured to respond to a GET /test with "Yes sir!" server.expect(MockHttpServer.Method.POST, "/", "Hello World").respondWith(200, "text/plain", "ABCD1234"); server.expect(MockHttpServer.Method.GET, "/test").respondWith(200, "text/plain", "Yes sir!"); // When a request for POST / arrives HttpPost req = new HttpPost(baseUrl + "/"); req.setEntity(new StringEntity("Hello World", HTTP.UTF_8)); ResponseHandler<String> handler = new BasicResponseHandler(); String responseBody = client.execute(req, handler); // Then the response is "ABCD1234" assertEquals("ABCD1234", responseBody); // When a request for GET /test arrives HttpGet get = new HttpGet(baseUrl + "/test"); handler = new BasicResponseHandler(); responseBody = client.execute(get, handler); // Then the response is "Yes sir!" assertEquals("Yes sir!", responseBody); }
From source file:it.simoneloru.ctmdroid.activities.TimetableActivity.java
private String callCtmSite() throws Exception { HttpResponse execute = null;// www. ja va 2 s . com HttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(); request.setURI(new URI(URI)); request.addHeader("Referer", URI); Cursor codeCursor = ctmDb.getRoad( Long.toString(getIntent().getLongExtra(getPackageName() + ".busStopCodeId", -1)), new String[] { CTMDroidDatabase.KEY_CODE }); String code = codeCursor.getString(0); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("mode", "1")); nameValuePairs.add(new BasicNameValuePair("stopcode", "-1")); nameValuePairs.add(new BasicNameValuePair("stopdescr", code)); nameValuePairs.add(new BasicNameValuePair("linenames", "-1")); nameValuePairs.add(new BasicNameValuePair("ptsearch", "Ricerca")); Calendar now = Calendar.getInstance(); nameValuePairs.add(new BasicNameValuePair("pt_day", Integer.toString(now.get(Calendar.DAY_OF_MONTH)))); nameValuePairs.add(new BasicNameValuePair("pt_month", Integer.toString(now.get(Calendar.MONTH) + 1))); nameValuePairs.add(new BasicNameValuePair("pt_year", Integer.toString(now.get(Calendar.YEAR)))); nameValuePairs.add(new BasicNameValuePair("PT_HH_FROM", Integer.toString(now.get(Calendar.HOUR_OF_DAY)))); Calendar later = new GregorianCalendar(); later.setTime(now.getTime()); later.add(Calendar.HOUR_OF_DAY, 1); nameValuePairs.add(new BasicNameValuePair("PT_HH_TO", Integer.toString(later.get(Calendar.HOUR_OF_DAY)))); nameValuePairs.add(new BasicNameValuePair("PT_MM_FROM", Integer.toString(now.get(Calendar.MINUTE)))); nameValuePairs.add(new BasicNameValuePair("PT_MM_TO", Integer.toString(later.get(Calendar.MINUTE)))); UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs); request.setEntity(urlEncodedFormEntity); execute = defaultHttpClient.execute(request); resultWebView = (WebView) findViewById(R.id.webview); BasicResponseHandler basicResponseHandler = new BasicResponseHandler(); String handleResponse = basicResponseHandler.handleResponse(execute); if (handleResponse.contains("Dati non disponibili")) { return NODATA; } else { String body = handleResponse.substring(handleResponse.indexOf("<body"), handleResponse.lastIndexOf("</body>")); String homehtm = CTMDroidUtil.LoadFile("home.htm", getResources()); Locale locale = this.getResources().getConfiguration().locale; if (!locale.equals(Locale.ITALY)) { body = CTMDroidUtil.bodyInEnglish(body); } homehtm = homehtm.replace("$placeholder$", body); Log.i("CTM", homehtm); resultWebView.loadDataWithBaseURL("file:///android-asset/", homehtm, "text/html", "utf-8", null); resultWebView.setTag(homehtm); return null; } }
From source file:managedbeans.UsuarioController.java
public void login() { System.out.println("Funcin login: Comenzando autenticacin"); FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); //LoginContext lc = null; try {/*from ww w . j ava 2 s . c o m*/ if (!hasIdentity()) { //Autenticacin con LDAP HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://inicio.diinf.usach.cl/webservice.php"); // Add your data List<BasicNameValuePair> nameValuePairs = new ArrayList<>(2); nameValuePairs.add(new BasicNameValuePair("user", nombre)); nameValuePairs.add(new BasicNameValuePair("pass", password)); nameValuePairs.add(new BasicNameValuePair("keyapi", MD5("c55ecd5c60a5a5b2bea1c92bbc45f8ab"))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); String responseString = new BasicResponseHandler().handleResponse(response); System.out.println(responseString); /* JSONParser parser = new JSONParser(null, null) Object obj = parser.parse(responseString); */ JSONObject jsonObject = new JSONObject(responseString); Boolean valido_response = (Boolean) jsonObject.get("pass_ok"); if (valido_response == null) { valido_response = false; } System.out.println("Datos Validos: " + valido_response); //FIN AUTENTICACIN LDAP request.login(nombre, jsonObject.getString("pass_ok")); if (valido_response) { System.out.println("SessionUtil: SessionScope created for " + nombre); JsfUtil.addSuccessMessage("Logeado con xito"); Usuario usuario = usuarioBussines.findByUid(nombre); setRoles(usuario.getRoles()); System.out.println("nombre de usuario: " + usuario.getNombre_usuario() + " - rol: " + usuario.getRoles().get(0).getTipo()); if (usuario.getRoles().get(0).getTipo().equals("COORDINADOR DOCENTE")) { FacesContext.getCurrentInstance().getExternalContext() .redirect("/easy-planning-web/faces/coordinador_docente/index.xhtml"); } else if (usuario.getRoles().get(0).getTipo().equals("PROFESOR")) { FacesContext.getCurrentInstance().getExternalContext() .redirect("/easy-planning-web/faces/profesor/index.xhtml"); } else { System.out.println("no se sabe el rol"); } error = false; } } else { System.out.println("SessionUtil: User allready logged"); error = false; } } catch (Exception e) { System.out.println("SessionUtil: User or password not found"); JsfUtil.addErrorMessage("El usuario y/o la contrasea no coinciden"); error = true; } }
From source file:com.mp3tunes.android.player.RemoteAlbumArtHandler.java
private String getRemoteArtworkForLocalTrack(Track t) { String id = "stYqie5s3hGAz_VW3cXxwQ"; String render = "json"; String album = t.getAlbumTitle(); String artist = t.getArtistName(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("_id", id)); params.add(new BasicNameValuePair("_render", render)); params.add(new BasicNameValuePair("album", album)); params.add(new BasicNameValuePair("artist", artist)); try {/*from w w w . j ava 2s . c o m*/ URI uri = URIUtils.createURI("http", "pipes.yahoo.com", -1, "/pipes/pipe.run", URLEncodedUtils.format(params, "UTF-8"), null); HttpGet get = new HttpGet(uri); Log.w("Mp3Tunes", "Url: " + get.getURI().toString()); HttpClient client = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(get, responseHandler); client.getConnectionManager().shutdown(); JSONObject obj = new JSONObject(response); JSONObject value = obj.getJSONObject("value"); JSONArray items = value.getJSONArray("items"); JSONObject item = items.getJSONObject(0); JSONObject image = item.getJSONObject("image"); return image.getString("url"); } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
From source file:com.da.img.SoStroyAllList0405.java
protected List<AuthorVo> executeAuthorList(String p_page, String p_author_id, String p_gnum) throws IOException, ClientProtocolException, URISyntaxException { DefaultHttpClient httpclient = new DefaultHttpClient(); List<AuthorVo> lst = new ArrayList<AuthorVo>(); AuthorVo authorVo = new AuthorVo(); try {//from w w w . j av a 2s . com HttpGet httpget = executeLogin(httpclient); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // http://story.soraspace.info/honor/honor_list_02.php // http://story.soraspace.info/honor/honor_list_03.php // http://story.soraspace.info/honor/honor_list_04.php // http://story.soraspace.info/honor/honor_list_05.php int max_page = 5; int init_page = 4; String listBody = "", strUrl = ""; for (int i = init_page; i <= max_page; i++) { strUrl = story_url + "honor_list_0" + String.valueOf(i) + ".php"; listBody = getDownloadUrl(httpclient, httpget, responseHandler, strUrl); listBody = listBody.substring(listBody.indexOf("<!-- START ? -->"), listBody.indexOf("<!-- END ? -->")); Matcher match = pattern_author.matcher(listBody); while (match.find()) { authorVo = new AuthorVo(); //System.out.println(match); String listurl = match.group(0); //System.out.println(listurl); String listurl1 = match.group(1); listurl1 = listurl1.replace("onClick=\"soraShowUserLayer('", "").replace(" ", ""); listurl1 = listurl1.substring(0, listurl1.indexOf("'")); System.out.println(listurl1); //System.out.println(listurl1.length()); String listurl2 = match.group(2); System.out.println(listurl2); authorVo.setAuthorSpan(listurl); authorVo.setAuthorId(listurl1); authorVo.setAuthorAlias(listurl2); lst.add(authorVo); } } } catch (Exception ex) { } return lst; }
From source file:com.postmark.PostmarkMailSender.java
@Override public void send(SimpleMailMessage message) throws MailException { HttpClient httpClient = new DefaultHttpClient(); PostmarkResponse theResponse = new PostmarkResponse(); try {//from w w w . j av a 2 s. c o m // Create post request to Postmark API endpoint HttpPost method = new HttpPost("http://api.postmarkapp.com/email"); // Add standard headers required by Postmark method.addHeader("Accept", "application/json"); method.addHeader("Content-Type", "application/json; charset=utf-8"); method.addHeader("X-Postmark-Server-Token", serverToken); method.addHeader("User-Agent", "Postmark-Java"); // Convert the message into JSON content String messageContents = UnicodeEscapeFilterWriter.escape(gson.toJson(message)); logger.log(Level.FINER, "Message contents: " + messageContents); // Add JSON as payload to post request StringEntity payload = new StringEntity(messageContents); payload.setContentEncoding(HTTP.UTF_8); method.setEntity(payload); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { String response = httpClient.execute(method, responseHandler); logger.log(Level.FINER, "Message response: " + response); theResponse = gson.fromJson(response, PostmarkResponse.class); theResponse.status = PostmarkResponseStatus.SUCCESS; } catch (HttpResponseException hre) { switch (hre.getStatusCode()) { case 401: case 422: logger.log(Level.SEVERE, "There was a problem with the email: " + hre.getMessage()); theResponse.setMessage(hre.getMessage()); theResponse.status = PostmarkResponseStatus.USERERROR; throw new MailSendException("Postmark returned: " + theResponse); case 500: logger.log(Level.SEVERE, "There has been an error sending your email: " + hre.getMessage()); theResponse.setMessage(hre.getMessage()); theResponse.status = PostmarkResponseStatus.SERVERERROR; throw new MailSendException("Postmark returned: " + theResponse); default: logger.log(Level.SEVERE, "There has been an unknow error sending your email: " + hre.getMessage()); theResponse.status = PostmarkResponseStatus.UNKNOWN; theResponse.setMessage(hre.getMessage()); throw new MailSendException("Postmark returned: " + theResponse); } } } catch (Exception e) { logger.log(Level.SEVERE, "There has been an error sending email: " + e.getMessage()); throw new MailSendException("There has been an error sending email", e); } finally { httpClient.getConnectionManager().shutdown(); } }