java编写http请求

1.使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接  

 

demo:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.mangocity.ziwoyou.bean.View;
import com.mangocity.ziwoyou.bean.ViewInfo;



public class ZiWoYouBaseService  {
    protected  final Logger log = Logger.getLogger(getClass());
	private String custId = null;
    private String apikey = null;
    private String serverHost = null;
    
	public String call (Map<String , String> bodyMap,String serviceName) throws Exception {
		String responseData = null;
        Map<String,String> map=new HashMap<String,String>();
        map.put("custId", getCustId());
        map.put("apiKey", getApikey());
        map.put("serverHost", getServerHost());
        map.put("serviceName", serviceName);
        responseData = get(bodyMap , map);
        System.out.println("响应json:\n"+responseData);
	    return responseData;
	}
	
	 /** 
     * 发送 get请求 
     */  
    public static String get(Map<String , String> bodyMap, Map<String,String> map) {  
    	HttpClient  httpclient = new DefaultHttpClient(); 
    	String responseContent = null;
    	BufferedReader in = null;
        try {
        	String custId = map.get("custId");
        	String apikey = map.get("apikey");
        	String serverHost = map.get("serverHost");
        	String serviceName = map.get("serviceName");
        	
        	List<NameValuePair> qparams = dealRequestBody(bodyMap, custId,
					apikey);
			HttpResponse response = sendGet(httpclient, serverHost,
					serviceName, qparams);  
            in = new BufferedReader(new InputStreamReader(response.getEntity()  
                    .getContent()));  
            StringBuffer sb = new StringBuffer("");  
            String line = "";  
            while ((line = in.readLine()) != null) {  
                sb.append(line);  
            }  
            in.close();  
            responseContent = sb.toString();  
            System.out.println(responseContent);
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (URISyntaxException e) {
			e.printStackTrace();
		} finally{
            try{
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        } 
        return responseContent;
    }
    
    /**
     * 发送http get请求
     * @param httpclient
     * @param serverHost
     * @param serviceName
     * @param qparams
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
	private static HttpResponse sendGet(HttpClient httpclient,
			String serverHost, String serviceName, List<NameValuePair> qparams)
			throws URISyntaxException, IOException, ClientProtocolException {
		URI uri = URIUtils.createURI("http", serverHost, -1, serviceName,URLEncodedUtils.format(qparams, "UTF-8"), null);
		HttpGet httpget = new HttpGet();
		httpget.setURI(uri);
		System.out.println(httpget.getURI());
		HttpResponse response = httpclient.execute(httpget);
		return response;
	}

    /**
     * 处理请求参数
     * @param bodyMap
     * @param custId
     * @param apikey
     * @return
     */
	private static List<NameValuePair> dealRequestBody(
			Map<String, String> bodyMap, String custId, String apikey) {
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("custId", custId));
		qparams.add(new BasicNameValuePair("apikey", apikey));
		Iterator<Map.Entry<String, String>> iter =  bodyMap.entrySet().iterator();
		while(iter.hasNext()){
			Entry<String , String> entry = iter.next();
			String key = entry.getKey();
			String value = entry.getValue();
			qparams.add(new BasicNameValuePair(key, value));
		}
		return qparams;
	}  
    
	public String getApikey() {
		return apikey;
	}

	public void setApikey(String apikey) {
		this.apikey = apikey;
	}

	public String getCustId() {
		return custId;
	}
	public void setCustId(String custId) {
		this.custId = custId;
	}

	public String getServerHost() {
		return serverHost;
	}

	public void setServerHost(String serverHost) {
		this.serverHost = serverHost;
	}
	
	public static void main(String[] args) {
		Map bodyMap = new HashMap();
		Map map = new HashMap();
		map.put("custId", "***");
        map.put("apikey", "********");
        map.put("serverHost", "*******");
        map.put("serviceName", "****");
        bodyMap.put("cityName", "北京,上海,广州");
        bodyMap.put("limit", "5");
	String responseData = get(bodyMap , map);//获取到的数据为xml
	ParseUtil<View> imageListDataParseUtil = new ParseUtil<View>();//转换xml数据
        View view =  imageListDataParseUtil.xmlToObject(responseData,View.class);
        for (ViewInfo vi : view.getViews()) {
			System.out.println(vi.getCityName());
		}
	}
}

    参考链接:https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.1.1/httpclient-contrib/docs/translated-tutorial/httpclient-tutorial-simplified-chinese.pdf

 

 

 

猜你喜欢

转载自lopez.iteye.com/blog/2223356