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

📄 httpsampler2.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
				res.setQueryString(postBody);
			} else if (method.equals(PUT)) {
                String putBody = sendPutData((PutMethod)httpMethod);
                res.setQueryString(putBody);
            }

            res.setRequestHeaders(getConnectionHeaders(httpMethod));

			int statusCode = client.executeMethod(httpMethod);

			// Request sent. Now get the response:
            instream = httpMethod.getResponseBodyAsStream();
            
            if (instream != null) {// will be null for HEAD
            
                Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
                if (responseHeader!= null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                    instream = new GZIPInputStream(instream);
                }
    
                //int contentLength = httpMethod.getResponseContentLength();Not visible ...
                //TODO size ouststream according to actual content length
                ByteArrayOutputStream outstream = new ByteArrayOutputStream(4*1024);
                        //contentLength > 0 ? contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
                byte[] buffer = new byte[4096];
                int len;
                boolean first = true;// first response
                while ((len = instream.read(buffer)) > 0) {
                    if (first) { // save the latency
                        res.latencyEnd();
                        first = false;
                    }
                    outstream.write(buffer, 0, len);
                }
    
                res.setResponseData(outstream.toByteArray());
                outstream.close();            

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

			// Now collect the results into the HTTPSampleResult:

			res.setSampleLabel(httpMethod.getURI().toString());
            // Pick up Actual path (after redirects)
            
			res.setResponseCode(Integer.toString(statusCode));
			res.setSuccessful(isSuccessCode(statusCode));

			res.setResponseMessage(httpMethod.getStatusText());

			String ct = null;
			org.apache.commons.httpclient.Header h 
                = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
			if (h != null)// Can be missing, e.g. on redirect
			{
				ct = h.getValue();
				res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
                res.setEncodingAndType(ct);
			}

			res.setResponseHeaders(getResponseHeaders(httpMethod));
			if (res.isRedirect()) {
				final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
				if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
					throw new IllegalArgumentException("Missing location header");
				}
				res.setRedirectLocation(headerLocation.getValue());
			}

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

			// Follow redirects and download page resources if appropriate:
			res = resultProcessing(areFollowingRedirect, frameDepth, res);

			log.debug("End : sample");
			if (httpMethod != null)
				httpMethod.releaseConnection();
			return res;
		} catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
		{
			res.sampleEnd();
			HTTPSampleResult err = errorResult(e, res);
			err.setSampleLabel("Error: " + url.toString());
			return err;
		} catch (IOException e) {
			res.sampleEnd();
			HTTPSampleResult err = errorResult(e, res);
			err.setSampleLabel("Error: " + url.toString());
			return err;
		} finally {
            JOrphanUtils.closeQuietly(instream);
			if (httpMethod != null)
				httpMethod.releaseConnection();
		}
	}

    /**
     * Set up the PUT data
     */
    private String sendPutData(PutMethod put) throws IOException {
        // Buffer to hold the put body, except file content
        StringBuffer putBody = new StringBuffer(1000);
        boolean hasPutBody = false;
        
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = put.getRequestHeader(HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0; 

        // If there are no arguments, we can send a file as the body of the request
        if(!hasArguments() && getSendFileAsPostBody()) {
            hasPutBody = true;
                
            FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(getFilename()),null); 
            put.setRequestEntity(fileRequestEntity);
                
            // We just add placeholder text for file content
            putBody.append("<actual file content, not shown here>");
        }
        // If none of the arguments have a name specified, we
        // just send all the values as the put body
        else if(getSendParameterValuesAsPostBody()) {
            hasPutBody = true;

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            final String contentEncoding = getContentEncoding();
            boolean haveContentEncoding = false;
            if(contentEncoding != null && contentEncoding.trim().length() > 0) {
                put.getParams().setContentCharset(contentEncoding);
                haveContentEncoding = true;
            }
                
            // Just append all the parameter values, and use that as the post body
            StringBuffer putBodyContent = new StringBuffer();
            PropertyIterator args = getArguments().iterator();
            while (args.hasNext()) {
                HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
                String value = null;
                if (haveContentEncoding){
                    value = arg.getEncodedValue(contentEncoding);
                } else {
                    value = arg.getEncodedValue();
                }
                putBodyContent.append(value);
            }
            String contentTypeValue = null;
            if(hasContentTypeHeader) {
                contentTypeValue = put.getRequestHeader(HEADER_CONTENT_TYPE).getValue();
            }
            StringRequestEntity requestEntity = new StringRequestEntity(putBodyContent.toString(), contentTypeValue, put.getRequestCharSet());
            put.setRequestEntity(requestEntity);
        }
        // Check if we have any content to send for body
        if(hasPutBody) {                
            // If the request entity is repeatable, we can send it first to
            // our own stream, so we can return it
            if(put.getRequestEntity().isRepeatable()) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                put.getRequestEntity().writeRequest(bos);
                bos.flush();
                // We get the posted bytes as UTF-8, since java is using UTF-8
                putBody.append(new String(bos.toByteArray() , "UTF-8")); // $NON-NLS-1$
                bos.close();
            }
            else {
                putBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
            }
            if(!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                if(getMimetype() != null && getMimetype().length() > 0) {
                    put.setRequestHeader(HEADER_CONTENT_TYPE, getMimetype());
                }
            }
            // Set the content length
            put.setRequestHeader(HEADER_CONTENT_LENGTH, Long.toString(put.getRequestEntity().getContentLength()));
            return putBody.toString();
        }
        else {
            return null;
        }        
    }
    
    /**
     * Class extending FilePart, so that we can send placeholder text
     * instead of the actual file content
     */
    private static class ViewableFilePart extends FilePart {
    	private boolean hideFileData;
    	
        public ViewableFilePart(String name, File file, String contentType, String charset) throws FileNotFoundException {
            super(name, file, contentType, charset);
            this.hideFileData = false;
        }
        
        public void setHideFileData(boolean hideFileData) {
        	this.hideFileData = hideFileData;
        }
        
        protected void sendData(OutputStream out) throws IOException {
        	// Check if we should send only placeholder text for the
        	// file content, or the real file content
        	if(hideFileData) {
        		out.write("<actual file content, not shown here>".getBytes("UTF-8"));
        	}
        	else {
        		super.sendData(out);
        	}
        }
    }    

    /**
	 * From the <code>HttpMethod</code>, store all the "set-cookie" key-pair
	 * values in the cookieManager of the <code>UrlConfig</code>.
	 * 
	 * @param method
	 *            <code>HttpMethod</code> which represents the request
	 * @param u
	 *            <code>URL</code> of the URL request
	 * @param cookieManager
	 *            the <code>CookieManager</code> containing all the cookies
	 */
    protected void saveConnectionCookies(HttpMethod method, URL u, CookieManager cookieManager) {
		if (cookieManager != null) {
            Header hdr[] = method.getResponseHeaders(HEADER_SET_COOKIE);            
			for (int i = 0; i < hdr.length; i++) {
                cookieManager.addCookieFromHeader(hdr[i].getValue(),u);
			}
		}
	}
	

	public void threadStarted() {
		log.debug("Thread Started");
        
		// Does not need to be synchronised, as all access is from same thread
        httpClients.set ( new HashMap() );	
    }

	public void threadFinished() {
		log.debug("Thread Finished");

        // Does not need to be synchronised, as all access is from same thread
		Map map = (Map)httpClients.get();

		if ( map != null ) {
			for ( Iterator it = map.entrySet().iterator(); it.hasNext(); )
			{
				Map.Entry entry = (Map.Entry) it.next();
				HttpClient cl = (HttpClient) entry.getValue();
                cl.getHttpConnectionManager().closeIdleConnections(-1000);// Closes the connection
			}
			map.clear();
		}
	}
}

⌨️ 快捷键说明

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