⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpsampler.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		}
		return headerBuf.toString();
	}

	/**
	 * Extracts all the required cookies for that particular URL request and
	 * sets them in the <code>HttpURLConnection</code> passed in.
	 * 
	 * @param conn
	 *            <code>HttpUrlConnection</code> which represents the URL
	 *            request
	 * @param u
	 *            <code>URL</code> of the URL request
	 * @param cookieManager
	 *            the <code>CookieManager</code> containing all the cookies
	 *            for this <code>UrlConfig</code>
	 */
	private String setConnectionCookie(HttpURLConnection conn, URL u, CookieManager cookieManager) {
		String cookieHeader = null;
		if (cookieManager != null) {
			cookieHeader = cookieManager.getCookieHeaderForURL(u);
			if (cookieHeader != null) {
				conn.setRequestProperty(HEADER_COOKIE, cookieHeader);
			}
		}
		return cookieHeader;
	}

	/**
	 * Extracts all the required headers for that particular URL request and
	 * sets them in the <code>HttpURLConnection</code> passed in
	 * 
	 * @param conn
	 *            <code>HttpUrlConnection</code> which represents the URL
	 *            request
	 * @param u
	 *            <code>URL</code> of the URL request
	 * @param headerManager
	 *            the <code>HeaderManager</code> containing all the cookies
	 *            for this <code>UrlConfig</code>
	 */
	private void setConnectionHeaders(HttpURLConnection conn, URL u, HeaderManager headerManager) {
        // Add all the headers from the HeaderManager
		if (headerManager != null) {
			CollectionProperty headers = headerManager.getHeaders();
			if (headers != null) {
				PropertyIterator i = headers.iterator();
				while (i.hasNext()) {
					Header header = (Header) i.next().getObjectValue();
					String n = header.getName();
					String v = header.getValue();
					conn.addRequestProperty(n, v);
				}
			}
		}
	}
    
    /**
     * Get all the headers for the <code>HttpURLConnection</code> passed in
     * 
     * @param conn
     *            <code>HttpUrlConnection</code> which represents the URL
     *            request
     * @return the headers as a string
     */
    private String getConnectionHeaders(HttpURLConnection conn) {
        // Get all the request properties, which are the headers set on the connection
        StringBuffer hdrs = new StringBuffer(100);
        Map requestHeaders = conn.getRequestProperties();
        Set headerFields = requestHeaders.entrySet();
        for(Iterator i = headerFields.iterator(); i.hasNext();) {
        	Map.Entry entry = (Map.Entry)i.next();
        	String headerKey=(String) entry.getKey();
            // Exclude the COOKIE header, since cookie is reported separately in the sample
            if(!HEADER_COOKIE.equalsIgnoreCase(headerKey)) {            
            	List values = (List) entry.getValue();// value is a List of Strings
            	for (int j=0;j<values.size();j++){            		
                    hdrs.append(headerKey);
                    hdrs.append(": "); // $NON-NLS-1$                
                    hdrs.append((String) values.get(j));
                    hdrs.append("\n"); // $NON-NLS-1$
            	}
            }
        }
        return hdrs.toString();
    }

	/**
	 * Extracts all the required authorization for that particular URL request
	 * and sets it in the <code>HttpURLConnection</code> passed in.
	 * 
	 * @param conn
	 *            <code>HttpUrlConnection</code> which represents the URL
	 *            request
	 * @param u
	 *            <code>URL</code> of the URL request
	 * @param authManager
	 *            the <code>AuthManager</code> containing all the cookies for
	 *            this <code>UrlConfig</code>
	 */
	private void setConnectionAuthorization(HttpURLConnection conn, URL u, AuthManager authManager) {
		if (authManager != null) {
			Authorization auth = authManager.getAuthForURL(u);
			if (auth != null) {
				conn.setRequestProperty(HEADER_AUTHORIZATION, auth.toBasicHeader());
			}
		}
	}

	/**
	 * Samples the URL passed in and stores the result in
	 * <code>HTTPSampleResult</code>, following redirects and downloading
	 * page resources as appropriate.
	 * <p>
	 * When getting a redirect target, redirects are not followed and resources
	 * are not downloaded. The caller will take care of this.
	 * 
	 * @param url
	 *            URL to sample
	 * @param method
	 *            HTTP method: GET, POST,...
	 * @param areFollowingRedirect
	 *            whether we're getting a redirect target
	 * @param frameDepth
	 *            Depth of this target in the frame structure. Used only to
	 *            prevent infinite recursion.
	 * @return results of the sampling
	 */
	protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {
		HttpURLConnection conn = null;

		String urlStr = url.toString();
		log.debug("Start : sample " + urlStr);

		HTTPSampleResult res = new HTTPSampleResult();
		res.setMonitor(isMonitor());
        
		res.setSampleLabel(urlStr);
		res.sampleStart(); // Count the retries as well in the time
		try {
			// Sampling proper - establish the connection and read the response:
			// Repeatedly try to connect:
			int retry;
			// Start with 0 so tries at least once, and retries at most MAX_CONN_RETRIES times
			for (retry = 0; retry <= MAX_CONN_RETRIES; retry++) {
				try {
					conn = setupConnection(url, method, res);
					// Attempt the connection:
					conn.connect();
					break;
				} catch (BindException e) {
					if (retry >= MAX_CONN_RETRIES) {
						log.error("Can't connect", e);
						throw e;
					}
					log.debug("Bind exception, try again");
					if (conn!=null) conn.disconnect();
					this.setUseKeepAlive(false);
					continue; // try again
				} catch (IOException e) {
					log.debug("Connection failed, giving up");
					throw e;
				}
			}
			if (retry > MAX_CONN_RETRIES) {
				// This should never happen, but...
				throw new BindException();
			}
			// Nice, we've got a connection. Finish sending the request:
			if (method.equals(POST)) {
				String postBody = sendPostData(conn);
				res.setQueryString(postBody);
            }
            else if (method.equals(PUT)) {
                String putBody = sendPutData(conn);
                res.setQueryString(putBody);
            }
			// Request sent. Now get the response:
			byte[] responseData = readResponse(conn, res);

			res.sampleEnd();
			// Done with the sampling proper.

			// Now collect the results into the HTTPSampleResult:

			res.setResponseData(responseData);

			int errorLevel = conn.getResponseCode();
            String respMsg = conn.getResponseMessage();
    		String hdr=conn.getHeaderField(0);
    		if (hdr == null) hdr="(null)";  // $NON-NLS-1$
            if (errorLevel == -1){// Bug 38902 - sometimes -1 seems to be returned unnecessarily
            	if (respMsg != null) {// Bug 41902 - NPE
	                try {
	                    errorLevel = Integer.parseInt(respMsg.substring(0, 3));
	                    log.warn("ResponseCode==-1; parsed "+respMsg+ " as "+errorLevel);
	                  } catch (NumberFormatException e) {
	                    log.warn("ResponseCode==-1; could not parse "+respMsg+" hdr: "+hdr);
	                  }
            	} else {
            		respMsg=hdr; // for result
                    log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= "+hdr);
            	}
            }
            if (errorLevel == -1) {
            	res.setResponseCode("(null)"); // $NON-NLS-1$
            } else {
			    res.setResponseCode(Integer.toString(errorLevel));
            }
			res.setSuccessful(isSuccessCode(errorLevel));

			if (respMsg == null) {// has been seen in a redirect
				respMsg=hdr; // use header (if possible) if no message found
			}
			res.setResponseMessage(respMsg);

			String ct = conn.getContentType();
			if (ct != null){
			    res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
                res.setEncodingAndType(ct);
			}

			res.setResponseHeaders(getResponseHeaders(conn));
			if (res.isRedirect()) {
				res.setRedirectLocation(conn.getHeaderField(HEADER_LOCATION));
			}

            // If we redirected automatically, the URL may have changed
            if (getAutoRedirects()){
                res.setURL(conn.getURL());
            }
            
			// Store any cookies received in the cookie manager:
			saveConnectionCookies(conn, url, getCookieManager());

			res = resultProcessing(areFollowingRedirect, frameDepth, res);

			log.debug("End : sample");
			return res;
		} catch (IOException e) {
			res.sampleEnd();
			// We don't want to continue using this connection, even if KeepAlive is set
            if (conn != null) { // May not exist
            	conn.disconnect();
            }
            conn=null; // Don't process again
			return errorResult(e, res);
		} finally {
			// calling disconnect doesn't close the connection immediately,
			// but indicates we're through with it. The JVM should close
			// it when necessary.
			disconnect(conn); // Disconnect unless using KeepAlive
		}
	}

	protected void disconnect(HttpURLConnection conn) {
		if (conn != null) {
			String connection = conn.getHeaderField(HEADER_CONNECTION);
			String protocol = conn.getHeaderField(0);
			if ((connection == null && (protocol == null || !protocol.startsWith(HTTP_1_1)))
					|| (connection != null && connection.equalsIgnoreCase(CONNECTION_CLOSE))) {
				conn.disconnect();
			}
		}
	}

	/**
	 * From the <code>HttpURLConnection</code>, store all the "set-cookie"
	 * key-pair values in the cookieManager of the <code>UrlConfig</code>.
	 * 
	 * @param conn
	 *            <code>HttpUrlConnection</code> which represents the URL
	 *            request
	 * @param u
	 *            <code>URL</code> of the URL request
	 * @param cookieManager
	 *            the <code>CookieManager</code> containing all the cookies
	 *            for this <code>UrlConfig</code>
	 */
	private void saveConnectionCookies(HttpURLConnection conn, URL u, CookieManager cookieManager) {
		if (cookieManager != null) {
			for (int i = 1; conn.getHeaderFieldKey(i) != null; i++) {
				if (conn.getHeaderFieldKey(i).equalsIgnoreCase(HEADER_SET_COOKIE)) {
					cookieManager.addCookieFromHeader(conn.getHeaderField(i), u);
				}
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -