HttpClient跨项目(跨服务器)调用步骤

HttpClient跨项目(跨服务器)调用方法例子
package XX.XX.XX;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientTest {
	
	public static void main(String[] args) {
		myPost();
	}
	
	/**
	 * @since 2013-8-14
	 * @Description: 以post方式请求网页 
	 * @throws
	 * void
	 */
	public static void myPost(){
		//目标URL
        String url = "http://127.0.0.1:8080/testssi/MyTest.action";  
        //创建一个默认的HttpClient  
        HttpClient httpclient = new DefaultHttpClient();  
        try {  
            //以post方式请求网页 
            HttpPost httppost = new HttpPost(url);  
            //添加HTTP POST参数  
            List  nvps = new ArrayList ();  
            nvps.add(new BasicNameValuePair("username", "cz"));  
            nvps.add(new BasicNameValuePair("password", "123"));  
  
            //将POST参数以UTF-8编码并包装成表单实体对象  
            httppost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));  
            //打印请求地址  
            System.out.println("executing request " + httppost.getRequestLine().getUri());  
            //创建响应处理器处理服务器响应内容  
            ResponseHandler responseHandler = new BasicResponseHandler();  
            //执行请求并获取结果  
            String responseBody = httpclient.execute(httppost, responseHandler);  
            System.out.println(responseBody);  
        }catch(Exception e){
        	e.printStackTrace();
        }finally {  
            // 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源  
            httpclient.getConnectionManager().shutdown();  
        } 
	}
	
	/**
	 * @since 2013-8-14
	 * @Description: 以get方式请求网页 
	 * @throws
	 * void
	 */
	public static void myGet(){
		//目标URL 
        String url = "http://127.0.0.1:8080/testssi/MyTest.action";  
        //创建一个默认的HttpClient  
        HttpClient httpclient = new DefaultHttpClient();  
        try {  
            //以get方式请求网页 
            HttpGet httpget = new HttpGet(url);  
            //打印请求地址  
            System.out.println("executing request " + httpget.getURI());  
            //创建响应处理器处理服务器响应内容  
            ResponseHandler responseHandler = new BasicResponseHandler();  
            //执行请求并获取结果  
            String responseBody = httpclient.execute(httpget, responseHandler);  
            System.out.println(responseBody);  
        }catch(Exception e){
        	e.printStackTrace();
        }finally {  
            // 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源  
            httpclient.getConnectionManager().shutdown();  
        }  
	}
}

你可能感兴趣的:(HttpClient跨项目(跨服务器)调用步骤)