使用HttpClient的方式調用接口的實例。
1 public class TestHttpClient { 2 3 public static void main(String[] args) { 4 // 請求接口地址 5 String url = ""; 6 // 請求參數 7 String userid = ""; 8 9 HttpClient httpclient = null; 10 PostMethod post = null; 11 try { 12 //創建連接 13 httpclient = new HttpClient(); 14 post = new PostMethod(url); 15 // 設置編碼方式 16 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); 17 // 添加參數 18 post.addParameter("userid", userid); 19 // 執行請求 20 httpclient.executeMethod(post); 21 // 接口返回信息 22 String info = new String(post.getResponseBody(), "UTF-8"); 23 System.out.println(info); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } finally { 27 // 關閉連接,釋放資源 28 post.releaseConnection(); 29 ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown(); 30 } 31 } 32 }