Java tutorial
/* * MyHttpClient.java * Created on 2011-5-25; Project to Colt2010; $Id: MyHttpClient.java 304 2013-04-20 12:11:12Z tristan $ * * Copyright (c) 2011, Xu Brothers and/or its affiliates. All rights reserved. * Xu Brothers PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.waku.common.http; import java.io.ByteArrayInputStream; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.io.DOMReader; import org.w3c.tidy.Configuration; import org.w3c.tidy.Tidy; /** * @versin $Rev: 304 $, $Date: 2013-04-20 20:11:12 +0800 (, 20 2013) $ * @author Jin */ @SuppressWarnings("deprecation") public class MyHttpClient { static Logger logger = Logger.getLogger(MyHttpClient.class.getName()); private static String getResponse(HttpClient httpclient, HttpRequestBase http) { try { logger.info("Executing ---> " + http.getRequestLine()); return httpclient.execute(http, new BasicResponseHandler()); } catch (Throwable e) { logger.info("Exception got ->", e); if (e.getMessage().equalsIgnoreCase("Internal Server Error")) { logger.info("Internal Server Error, seems not recovery-able!"); return null; } logger.info("======== Retry will start after 10 sec ----->"); try { Thread.sleep(10000); } catch (InterruptedException ie) { ie.printStackTrace(); } return getResponse(httpclient, http); } } private static Document getResponseAndConvertToDom(HttpClient httpclient, HttpRequestBase httppost) { String response = getResponse(httpclient, httppost); if (response == null) { return null; } Tidy tidy = new Tidy(); tidy.setShowWarnings(false); tidy.setCharEncoding(Configuration.UTF8); return new DOMReader().read(tidy.parseDOM(new ByteArrayInputStream(response.getBytes()), null)); } public static Document getAsDom4jDoc(String url) { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler()); try { HttpGet httpGet = new HttpGet(url); return getResponseAndConvertToDom(httpclient, httpGet); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } } public static Document getAsDom4jDoc(String url, MultipartEntity reqEntity) { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler()); try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(reqEntity); return getResponseAndConvertToDom(httpclient, httpPost); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } } }