HttpClientの使い方


コアメソッドを送信します.
 
いくつかの注釈は、注釈を見ることができます.
package org.search.core.http;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.utils.stream.StreamUtils;

/**
 * Get      
 * @author Administrator
 *
 */
public class HttpFetcher {
	
	/**
	 *  GET      
	 * @param siteId
	 * @param url
	 * @return
	 */
	public static String fetcher_Get(String siteId, String url){
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			CookieStore cookies = CookiesStore.getInstance().getCookies(siteId);
			if(cookies != null)//  Cookies
				client.setCookieStore(cookies);
			HttpResponse resp = client.execute(get);
			int status = resp.getStatusLine().getStatusCode();
			/**       30*  ,         */
			if(status == HttpStatus. SC_MOVED_TEMPORARILY ||
					status == HttpStatus.SC_MOVED_PERMANENTLY||
					status == HttpStatus.SC_SEE_OTHER||
					status == HttpStatus.SC_TEMPORARY_REDIRECT){
				Header[] header = resp.getHeaders("location");
				if(header.length >0){
					String location = header[0].getValue();
					if(location == null || "".equalsIgnoreCase(location)){
						location = "/";
					}
					fetcher_Get(siteId, location);
				}
			}else if(status == HttpStatus.SC_OK){
				//  Cookies
				CookiesStore.getInstance().storeCookies(siteId, client.getCookieStore());
				return StreamUtils.converStreamToStr(resp.getEntity().getContent(), true);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static void main(String[] args) {
		String content = 
			HttpFetcher.fetcher_Get("baidu", 
					"http://www.baidu.com/s?bs=httpclient+%CF%C2%D4%D8&f=8&wd=httpclient+");
		System.out.println(content);
	}
}