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

📄 httpsampler2.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
			httpClient.setHostConfiguration(hc);
			map.put(hc, httpClient);
            // These items don't change, so only need to be done once
            if (useProxy) {
                if (PROXY_USER.length() > 0){
                    httpClient.getState().setProxyCredentials(
                        new AuthScope(PROXY_HOST,PROXY_PORT,null,AuthScope.ANY_SCHEME),
                        new NTCredentials(PROXY_USER,PROXY_PASS,localHost,PROXY_DOMAIN)
                    );
                }
            }

		}

		// Allow HttpClient to handle the redirects:
		httpMethod.setFollowRedirects(getAutoRedirects());

		// a well-behaved browser is supposed to send 'Connection: close'
		// with the last request to an HTTP server. Instead, most browsers
		// leave it to the server to close the connection after their
		// timeout period. Leave it to the JMeter user to decide.
		if (getUseKeepAlive()) {
			httpMethod.setRequestHeader(HEADER_CONNECTION, KEEP_ALIVE);
		} else {
			httpMethod.setRequestHeader(HEADER_CONNECTION, CONNECTION_CLOSE);
		}

		setConnectionHeaders(httpMethod, u, getHeaderManager());
		String cookies = setConnectionCookie(httpMethod, u, getCookieManager());

        setConnectionAuthorization(httpClient, u, getAuthManager());

        if (res != null) {
            res.setURL(u);
            res.setCookies(cookies);
		}

		return httpClient;
	}

    /**
     * Set any default request headers to include
     * 
     * @param httpMethod the HttpMethod used for the request
     */
	protected void setDefaultRequestHeaders(HttpMethod httpMethod) {
        // Method left empty here, but allows subclasses to override
	}

	/**
	 * Gets the ResponseHeaders
	 * 
	 * @param method
	 *            connection from which the headers are read
	 * @return string containing the headers, one per line
	 */
	protected String getResponseHeaders(HttpMethod method) {
		StringBuffer headerBuf = new StringBuffer();
		org.apache.commons.httpclient.Header rh[] = method.getResponseHeaders();
		headerBuf.append(method.getStatusLine());// header[0] is not the status line...
		headerBuf.append("\n"); // $NON-NLS-1$

		for (int i = 0; i < rh.length; i++) {
			String key = rh[i].getName();
			headerBuf.append(key);
			headerBuf.append(": "); // $NON-NLS-1$
			headerBuf.append(rh[i].getValue());
			headerBuf.append("\n"); // $NON-NLS-1$
		}
		return headerBuf.toString();
	}

	/**
	 * Extracts all the required cookies for that particular URL request and
	 * sets them in the <code>HttpMethod</code> passed in.
	 * 
	 * @param method <code>HttpMethod</code> for the request
	 * @param u <code>URL</code> of the request
	 * @param cookieManager the <code>CookieManager</code> containing all the cookies
     * @return a String containing the cookie details (for the response)
     * May be null
	 */
	private String setConnectionCookie(HttpMethod method, URL u, CookieManager cookieManager) {        
        String cookieHeader = null;
        if (cookieManager != null) {
            cookieHeader = cookieManager.getCookieHeaderForURL(u);
            if (cookieHeader != null) {
                method.setRequestHeader(HEADER_COOKIE, cookieHeader);
            }
        }
		return cookieHeader;
	}

	/**
	 * Extracts all the required non-cookie headers for that particular URL request and
	 * sets them in the <code>HttpMethod</code> passed in
	 * 
	 * @param method
	 *            <code>HttpMethod</code> which represents the 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(HttpMethod method, URL u, HeaderManager headerManager) {
        // Set all the headers from the HeaderManager
		if (headerManager != null) {
			CollectionProperty headers = headerManager.getHeaders();
			if (headers != null) {
				PropertyIterator i = headers.iterator();
				while (i.hasNext()) {
					org.apache.jmeter.protocol.http.control.Header header 
                    = (org.apache.jmeter.protocol.http.control.Header) 
                       i.next().getObjectValue();
					String n = header.getName();
					// Don't allow override of Content-Length
					// This helps with SoapSampler hack too
					// TODO - what other headers are not allowed?
					if (! HEADER_CONTENT_LENGTH.equalsIgnoreCase(n)){
						String v = header.getValue();
						method.addRequestHeader(n, v);
					}
				}
			}
		}
	}
    
    /**
     * Get all the request headers for the <code>HttpMethod</code>
     * 
     * @param method
     *            <code>HttpMethod</code> which represents the request
     * @return the headers as a string
     */
    private String getConnectionHeaders(HttpMethod method) {
        // Get all the request headers
        StringBuffer hdrs = new StringBuffer(100);        
        Header[] requestHeaders = method.getRequestHeaders();
        for(int i = 0; i < requestHeaders.length; i++) {
            // Exclude the COOKIE header, since cookie is reported separately in the sample
            if(!HEADER_COOKIE.equalsIgnoreCase(requestHeaders[i].getName())) {
                hdrs.append(requestHeaders[i].getName());
                hdrs.append(": "); // $NON-NLS-1$
                hdrs.append(requestHeaders[i].getValue());
                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>HttpMethod</code> passed in.
	 * 
	 * @param client the HttpClient object
	 * 
	 * @param u
	 *            <code>URL</code> of the URL request
	 * @param authManager
	 *            the <code>AuthManager</code> containing all the authorisations for
	 *            this <code>UrlConfig</code>
	 */
    private void setConnectionAuthorization(HttpClient client, URL u, AuthManager authManager) {
		HttpParams params = client.getParams();
		if (authManager != null) {
            Authorization auth = authManager.getAuthForURL(u);
            if (auth != null) {
                    String username = auth.getUser();
                    String realm = auth.getRealm();
                    String domain = auth.getDomain();
                    if (log.isDebugEnabled()){
                        log.debug(username + " >  D="+ username + " D="+domain+" R="+realm);
                    }
					client.getState().setCredentials(
                            new AuthScope(u.getHost(),u.getPort(),
                            		realm.length()==0 ? null : realm //"" is not the same as no realm
                            		,AuthScope.ANY_SCHEME),
                            // NT Includes other types of Credentials
                            new NTCredentials(
									username, 
                                    auth.getPass(), 
                                    localHost,
									domain
							));
					// We have credentials - should we set pre-emptive authentication?
					if (canSetPreEmptive){
						log.debug("Setting Pre-emptive authentication");
						params.setBooleanParameter(HTTP_AUTHENTICATION_PREEMPTIVE, true);
					}
			}
            else
            {
                client.getState().clearCredentials();
                if (canSetPreEmptive){
                	params.setBooleanParameter(HTTP_AUTHENTICATION_PREEMPTIVE, false);
                }
            }
		}
        else
        {
            client.getState().clearCredentials();
        }
	}

	/**
	 * 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) {

		String urlStr = url.toString();

		log.debug("Start : sample " + urlStr);
		log.debug("method " + method);

        HttpMethodBase httpMethod = null;

		HTTPSampleResult res = new HTTPSampleResult();
		res.setMonitor(isMonitor());
        
		res.setSampleLabel(urlStr); // May be replaced later
        res.setHTTPMethod(method);
		res.sampleStart(); // Count the retries as well in the time
        HttpClient client = null;
        InputStream instream = null;
		try {
			// May generate IllegalArgumentException
			if (method.equals(POST)) {
			    httpMethod = new PostMethod(urlStr);
			} else if (method.equals(PUT)){
			    httpMethod = new PutMethod(urlStr);
			} else if (method.equals(HEAD)){
			    httpMethod = new HeadMethod(urlStr);
			} else if (method.equals(TRACE)){
			    httpMethod = new TraceMethod(urlStr);
			} else if (method.equals(OPTIONS)){
			    httpMethod = new OptionsMethod(urlStr);
			} else if (method.equals(DELETE)){
			    httpMethod = new DeleteMethod(urlStr);
			} else if (method.equals(GET)){
			    httpMethod = new GetMethod(urlStr);
			} else {
				log.error("Unexpected method (converted to GET): "+method);
			    httpMethod = new GetMethod(urlStr);
			}

			// Set any default request headers
			setDefaultRequestHeaders(httpMethod);
            // Setup connection
			client = setupConnection(url, httpMethod, res);
			// Handle the various methods
			if (method.equals(POST)) {
				String postBody = sendPostData((PostMethod)httpMethod);

⌨️ 快捷键说明

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