HttpClient跨項目(服務端)調用方法例子java
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 <NameValuePair> nvps = new ArrayList <NameValuePair>(); 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<String> 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<String> responseHandler = new BasicResponseHandler(); //執行請求並獲取結果 String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); }catch(Exception e){ e.printStackTrace(); }finally { // 當再也不須要HttpClient實例時,關閉鏈接管理器以確保釋放全部佔用的系統資源 httpclient.getConnectionManager().shutdown(); } } }