天天看點

Http模拟請求工具類

/**
	 *  POST 請求
	 * @param url
	 * @param paramMap
	 * @return
	 */
	public  Map<String, Object> sendPost(String url,Map<String, Object> paramMap){
		//【1】 建立 一個請求用戶端,
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response =null;
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//【2】建立一個 get/post 請求
			HttpPost post = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5000).build();//設定請求和傳輸逾時時間
			post.setConfig(requestConfig);
			//【3】設定請求頭資訊
			//如果傳送"application/xml"格式,選擇ContentType.APPLICATION_XML
			post.setHeader("Content-type",String.valueOf(ContentType.APPLICATION_JSON)); //請求的媒體類型資訊
			post.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //使用者代理,包含了用戶端的浏覽器資訊
			post.setHeader("accept","application/json");//告訴伺服器目前請求所支援的資料類型
			//【4-1】設定參數  方式1
			JSONObject jsonParam = new JSONObject();
			for (String key : paramMap.keySet()) {
				jsonParam.put(key,paramMap.get(key));
			}
			post.setEntity(new StringEntity(jsonParam.toJSONString(), Charset.forName("utf-8")));
			// 【5】執行請求
			logger.info("執行請求,請求位址:"+url);
			response = client.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			String resStr ="";
			InputStream content = response.getEntity().getContent();
			resStr = inputStream2String(content);
			// 【6】擷取結果狀态
			resMap.put("code",statusCode);
			resMap.put("resmsg",resStr);
		} catch (Exception e){
			resMap.put("code",1);
			resMap.put("resmsg",e.getMessage());
			logger.info("請求:"+url+" 異常:"+e.getMessage());
			e.printStackTrace();
		}finally {
			try {
	            if (response != null) {
	                response.close();
	            }
	            client.close();
	        } catch (IOException e1) {
	            e1.printStackTrace();
	        }
		}
		return resMap;
	}
	
    /**
     * post方式送出表單(模拟使用者登入請求)
     */
    public static void doFormPost(String url,Map<String, Object> paramMap) {
    	
        //【1】 建立 httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //【2】建立httppost
        HttpPost httppost = new HttpPost(url);
        //【3】處理參數
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        UrlEncodedFormEntity entity = null;
        try {
        	for (Entry<String, Object> entry : paramMap.entrySet()) {
        		formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
        	}
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            //【4】設定參數
            httppost.setEntity(entity);
            logger.info("executing request " + httppost.getURI());
            //【5】執行請求
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 關閉連接配接,釋放資源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	
	/**
	 * 模拟PUT請求
	 * @param url
	 * @param paramMap
	 * @return
	 */
	public  static Map<String, Object> sendPut(String url,Map<String, Object> paramMap){
		//【1】 建立 一個請求用戶端,
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response =null;
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//【2】建立一個 get/post 請求
			HttpPut put = new HttpPut(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5000).build();//設定請求和傳輸逾時時間
			put.setConfig(requestConfig);
			//【3】設定請求頭資訊
			put.setHeader("Content-type",String.valueOf(ContentType.APPLICATION_JSON)); //請求的媒體類型資訊
			put.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //使用者代理,包含了用戶端的浏覽器資訊
			put.setHeader("accept","application/json");//告訴伺服器目前請求所支援接收的資料類型
			//【4-1】設定參數  方式1
			JSONObject jsonParam = new JSONObject();
			for (String key : paramMap.keySet()) {
				jsonParam.put(key,paramMap.get(key));
			}
			put.setEntity(new StringEntity(jsonParam.toJSONString(), Charset.forName("utf-8")));
			// 【5】執行請求
			response = client.execute(put);
			int statusCode = response.getStatusLine().getStatusCode();
			String resStr ="";
			InputStream content = response.getEntity().getContent();
			resStr = inputStream2String(content);
			// 【6】擷取結果狀态
			resMap.put("code",statusCode);
			resMap.put("resmsg",resStr);
		} catch (Exception e){
			resMap.put("code",1);
			resMap.put("resmsg",e.getMessage());
			logger.info("請求:"+url+" 異常:"+e.getMessage());
			e.printStackTrace();
		}finally {
			try {
	            if (response != null) {
	                response.close();
	            }
	            client.close();
	        } catch (IOException e1) {
	            e1.printStackTrace();
	        }
		}
		return resMap;
	}
	
	
	
	//從流中讀取傳回資料
	public static String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}