httpClient get請求

官網下載:httpcomponents-client-4.5.2-bin.zipweb

須要的 jar:httpclient-4.5.2.jar、httpclient-cache-4.5.2.jar、httpcore-4.4.4.jarapache

 使用 HttpClient 須要如下 6 個步驟: 
  1. 建立 HttpClient 的實例 
  2. 建立某種鏈接方法的實例,在這裏是 GetMethod。在 GetMethod 的構造函數中傳入待鏈接的地址 
  3. 調用第一步中建立好的實例的 execute 方法來執行第二步中建立好的 method 實例 
  4. 讀 response 
  5. 釋放鏈接。不管執行方法是否成功,都必須釋放鏈接 
  6. 對獲得後的內容進行處理 json

客戶端代碼示例:數組

public static void main(String[] args) {
        // 第一個 sendHttpPost
        HttpDemo1 httpDemo1 = new HttpDemo1();
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "httpClient Get 測試");
//        JSONObject jsonStr = new JSONObject();
//        jsonStr.put("name", "httpClient Get 測試");
        String httpUrl = "http://localhost:8080/web1/servletTestCallBack.hts";
        String result = httpDemo1.sendHttpGet(httpUrl, map);
        System.out.println("result:" + result);
    }服務器

public String sendHttpGet(String httpUrl,Map<String, String> map){
        String result = ""; 
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String name = e.getKey();
            String value = e.getValue();
            NameValuePair pair = new BasicNameValuePair(name, value);
            params.add(pair);
        }        
        //要傳遞的參數.
        String url = httpUrl+"?" + URLEncodedUtils.format(params, HTTP.UTF_8);
        
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpClient httpClient = null;
        
        try{
            httpClient = new DefaultHttpClient();    
            //設置等待數據超時時間 120秒
            httpClient.getParams().setParameter("http.socket.timeout",2*1000*60);
            //設置請求超時 30秒
            httpClient.getParams().setParameter("http.connection.timeout",1*1000*30);    
            if (url == null || "".equals(url)) {
                return result;
            }
            //建立HttpGet對象
            HttpGet httpreq = new HttpGet(url);
            
            HttpResponse response = null;
            //使用DefaultHttpClient類的execute方法發送HTTP GET請求,並返回HttpResponse對象。
            response = httpclient.execute(httpreq);
            
            if (response == null) {
                return result;
            }
            //請求成功響應,讀取返回數據
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(),"utf-8");
            }else{
                System.out.println("HTTP GET請求無響應");
            } 
            
            return result;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally{
            try{
                httpClient.getConnectionManager().shutdown();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }socket

服務器響應代碼:ide

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {函數

        request.setCharacterEncoding("UTF-8");
        //獲得客戶端發送過來內容的類型
        System.out.println("客戶端發送過來內容的類型:" + request.getContentType());
        String name = request.getParameter("name");
        
        //獲取request對象以ISO8859-1字符編碼接收到的原始數據的字節數組,而後經過字節數組以指定的編碼構建字符串,解決亂碼問題。
        name = new String(name.getBytes("ISO8859-1"),"UTF-8");
        System.out.println("客戶端傳遞的參數name:" + name);
        //響應客戶端
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print("接受到信息,ok!");
    }測試

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }this

相關文章
相關標籤/搜索