How to remove HTML from a text string in Java

It’s smart to have HTML script attacks on your radar; they can cause some major headaches. Today we are going to look at how to filter out scripts from a text string, giving you an extra layer of protection against this threat. Not only that, we are going to get this done in a real hurry.

First things first, we need our library. We are going to dynamically compile this with Jitpack, so we need to add some references to pom.xml.





Now call editTextRemoveHtml, as we have demonstrated here:

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.EditTextApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");EditTextApi apiInstance = new EditTextApi();RemoveHtmlFromTextRequest request = new RemoveHtmlFromTextRequest(); // RemoveHtmlFromTextRequest | Input requesttry {RemoveHtmlFromTextResponse result = apiInstance.editTextRemoveHtml(request);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling EditTextApi#editTextRemoveHtml");e.printStackTrace();}

And the API does the hard work for us! Any HTML — and the potential hazards they carry — have now been stripped out of our string.

Image for post

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store