Posts

Showing posts with the label HttpClient

How to convert HttpResponse to String in Java

Following code snippet explains how to convert HttpResponse object to String in Java Steps Call httpclient.execute() Get the InputStream from the response Convert the InputStream to ByteArrayOutputStream Convert the ByteArrayOutputStream to String Close the request and InputStream private String executeAndGetResponse(HttpRequestBase request) throws IOException, ClientProtocolException, Exception, UnsupportedEncodingException { HttpResponse response = httpClient.execute(request); InputStream inputStream = response.getEntity().getContent(); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } String strRes = result.toString(StandardCharsets.UTF_8.name()); request.releaseConnection(); inputStream.close(); return strRes; }

Jakarta Commons HttpClient API Example

The Jakarta Commons HttpClient component provides API's for accessing HTTP Resources. We can download HttpClient from Apache and use it. The general process for using HttpClient consists of a number of steps: Create an instance of HttpClient . Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor. Tell HttpClient to execute the method. Read the response. Release the connection. Deal with the response. The following example shows, how we can use HttpClient for Submiting a form data to a URL. import java.io.IOException; import java.util.MissingResourceException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; public class FundaHttpClient { public static boolean httpPost(HttpServletRequest request) { //UR...