类org.apache.commons.httpclient.HttpException源码实例Demo

下面列出了怎么用org.apache.commons.httpclient.HttpException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: OfficeAutomatic-System   文件: HttpUtil.java
public static String sendGet(String urlParam) throws HttpException, IOException {
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建GET请求方法实例对象
    GetMethod getMethod = new GetMethod(urlParam);
    // 设置post请求超时时间
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    getMethod.addRequestHeader("Content-Type", "application/json");

    httpClient.executeMethod(getMethod);

    String result = getMethod.getResponseBodyAsString();
    getMethod.releaseConnection();
    return result;
}
 
源代码2 项目: boubei-tss   文件: AbstractTest4.java
public static void callAPI(String url, String user, String uToken) throws HttpException, IOException {
	if(url.indexOf("?") < 0) {
		url += "?uName=" +user+ "&uToken=" + uToken;
	}
	else {
		url += "&uName=" +user+ "&uToken=" + uToken;
	}
	PostMethod postMethod = new PostMethod(url);
	postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

    // 最后生成一个HttpClient对象,并发出postMethod请求
    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if(statusCode == 200) {
        System.out.print("返回结果: ");
        String soapResponseData = postMethod.getResponseBodyAsString();
        System.out.println(soapResponseData);     
    }
    else {
        System.out.println("调用失败!错误码:" + statusCode);
    }
}
 
源代码3 项目: alfresco-repository   文件: SolrQueryHTTPClient.java
protected JSONResult postSolrQuery(HttpClient httpClient, String url, JSONObject body, SolrJsonProcessor<?> jsonProcessor, String spellCheckParams)
            throws UnsupportedEncodingException, IOException, HttpException, URIException,
            JSONException
{
    JSONObject json = postQuery(httpClient, url, body);
    if (spellCheckParams != null)
    {
        SpellCheckDecisionManager manager = new SpellCheckDecisionManager(json, url, body, spellCheckParams);
        if (manager.isCollate())
        {
            json = postQuery(httpClient, manager.getUrl(), body);
        }
        json.put("spellcheck", manager.getSpellCheckJsonValue());
    }

        JSONResult results = jsonProcessor.getResult(json);

        if (s_logger.isDebugEnabled())
        {
            s_logger.debug("Sent :" + url);
            s_logger.debug("   with: " + body.toString());
            s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
        }
        
        return results;
}
 
源代码4 项目: Knowage-Server   文件: DataSetFactory.java
private static RESTDataSet manageSolrDataSet(JSONObject jsonConf, List<DataSetParameterItem> parameters)
		throws JSONException, HttpException, HMACSecurityException, IOException {
	SolrDataSet res = null;

	HashMap<String, String> parametersMap = new HashMap<String, String>();
	if (parameters != null) {
		for (Iterator iterator = parameters.iterator(); iterator.hasNext();) {
			DataSetParameterItem dataSetParameterItem = (DataSetParameterItem) iterator.next();
			parametersMap.put(dataSetParameterItem.getDefaultValue(), dataSetParameterItem.getName());
		}
	}

	String solrType = jsonConf.getString(SolrDataSetConstants.SOLR_TYPE);
	Assert.assertNotNull(solrType, "Solr type cannot be null");
	res = solrType.equalsIgnoreCase(SolrDataSetConstants.TYPE.DOCUMENTS.name()) ? new SolrDataSet(jsonConf, parametersMap)
			: new FacetSolrDataSet(jsonConf, parametersMap);
	res.setDsType(DataSetConstants.DS_SOLR_NAME);

	if (!jsonConf.has(SolrDataSetConstants.SOLR_FIELDS)) {
		JSONArray solrFields = res.getSolrFields();
		jsonConf.put(SolrDataSetConstants.SOLR_FIELDS, solrFields);
		res.setConfiguration(jsonConf.toString());
	}
	res.setSolrQueryParameters(res.getSolrQuery(), res.getParamsMap());
	return res;
}
 
源代码5 项目: Knowage-Server   文件: OAuth2Client.java
private String sendHttpPost(PostMethod httppost) throws HttpException, IOException, JSONException {
	HttpClient httpClient = getHttpClient();
	int statusCode = httpClient.executeMethod(httppost);
	byte[] response = httppost.getResponseBody();
	if (statusCode != 200) {
		logger.error("Error while getting access token from OAuth2 provider: server returned statusCode = " + statusCode);
		LogMF.error(logger, "Server response is:\n{0}", new Object[] { new String(response) });
		throw new SpagoBIRuntimeException("Error while getting access token from OAuth2 provider: server returned statusCode = " + statusCode);
	}

	String responseStr = new String(response);
	LogMF.debug(logger, "Server response is:\n{0}", responseStr);
	JSONObject jsonObject = new JSONObject(responseStr);
	String accessToken = jsonObject.getString("access_token");

	return accessToken;
}
 
源代码6 项目: Kylin   文件: RestClient.java
public void wipeCache(String type, String action, String name) throws IOException {
    String url = baseUrl + "/cache/" + type + "/" + name + "/" + action;
    HttpMethod request = new PutMethod(url);

    try {
        int code = client.executeMethod(request);
        String msg = Bytes.toString(request.getResponseBody());

        if (code != 200)
            throw new IOException("Invalid response " + code + " with cache wipe url " + url + "\n" + msg);

    } catch (HttpException ex) {
        throw new IOException(ex);
    } finally {
        request.releaseConnection();
    }
}
 
源代码7 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testRemoveTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
源代码8 项目: document-management-system   文件: MailUtils.java
/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 */
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
	HttpClient httpclient = new HttpClient();

	// Prepare a request object
	HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
	method.setQueryString(new NameValuePair[]{new NameValuePair("url", fullUrl)});
	httpclient.executeMethod(method);
	InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
	StringWriter sw = new StringWriter();
	int c;
	while ((c = isr.read()) != -1)
		sw.write(c);
	isr.close();
	method.releaseConnection();

	return sw.toString();
}
 
源代码9 项目: development   文件: RequestHandlerBase.java
/**
 * Will write all request headers stored in the request to the method that
 * are not in the set of banned headers.
 * The Accept-Endocing header is also changed to allow compressed content
 * connection to the server even if the end client doesn't support that. 
 * A Via headers is created as well in compliance with the RFC.
 * 
 * @param method The HttpMethod used for this connection
 * @param request The incoming request
 * @throws HttpException 
 */
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    Enumeration headers = request.getHeaderNames();
    String connectionToken = request.getHeader("connection");
    
    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));
        
        if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
            Enumeration value = request.getHeaders(name);
            while (value.hasMoreElements()) {
                method.addRequestHeader(name, (String) value.nextElement());
            } 
        } 
    } 
    
    setProxySpecificHeaders(method, request);
}
 
源代码10 项目: knopflerfish.org   文件: MultipartPostMethod.java
/**
 * Adds a <tt>Content-Type</tt> request header.
 *
 * @param state current state of http requests
 * @param conn the connection to use for I/O
 *
 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
 *                     can be recovered from.
 * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
 *                    cannot be recovered from.
 * 
 * @since 3.0
 */
protected void addContentTypeRequestHeader(HttpState state,
                                             HttpConnection conn)
throws IOException, HttpException {
    LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader("
              + "HttpState, HttpConnection)");

    if (!parameters.isEmpty()) {
        StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
        if (Part.getBoundary() != null) {
            buffer.append("; boundary=");
            buffer.append(Part.getBoundary());
        }
        setRequestHeader("Content-Type", buffer.toString());
    }
}
 
源代码11 项目: Hue-Ctrip-DI   文件: YarnJobCrawlerTask.java
private List<YarnJobsDo> getJobList(long maxStartTime)
		throws HttpException, IOException {
	List<YarnJobsDo> jobsList = new ArrayList<YarnJobsDo>();

	JSONObject json = getJson();
	JSONObject jobs = (JSONObject) json.get("jobs");
	JSONArray jobArray = (JSONArray) jobs.get("job");
	@SuppressWarnings("unchecked")
	ListIterator<JSONObject> iterator = jobArray.listIterator();
	while (iterator.hasNext()) {
		JSONObject jobObject = iterator.next();
		long startTime = jobObject.getLong("startTime");
		if (startTime > maxStartTime) {
			YarnJobsDo yarnJobsDo = toYarnJobsDo(jobObject);
			jobsList.add(yarnJobsDo);
		}
	}
	return jobsList;
}
 
源代码12 项目: knopflerfish.org   文件: ExpectContinueMethod.java
/**
 * Sets the <tt>Expect</tt> header if it has not already been set, 
 * in addition to the "standard" set of headers.
 *
 * @param state the {@link HttpState state} information associated with this method
 * @param conn the {@link HttpConnection connection} used to execute
 *        this HTTP method
 *
 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
 *                     can be recovered from.
 * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
 *                    cannot be recovered from.
 */
protected void addRequestHeaders(HttpState state, HttpConnection conn)
throws IOException, HttpException {
    LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)");
    
    super.addRequestHeaders(state, conn);
    // If the request is being retried, the header may already be present
    boolean headerPresent = (getRequestHeader("Expect") != null);
    // See if the expect header should be sent
    // = HTTP/1.1 or higher
    // = request body present

    if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) 
    && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) 
    && hasRequestContent())
    {
        if (!headerPresent) {
            setRequestHeader("Expect", "100-continue");
        }
    } else {
        if (headerPresent) {
            removeRequestHeader("Expect");
        }
    }
}
 
源代码13 项目: realtime-analytics   文件: Simulator.java
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
            JsonMappingException, UnsupportedEncodingException, HttpException {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> m = new HashMap<String, Object>();

        m.put("si", "12345");
        m.put("ct", System.currentTimeMillis());
        
        String payload = mapper.writeValueAsString(m);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
//      method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
        int status = client.executeMethod(method);
        System.out.println(Arrays.toString(method.getResponseHeaders()));
        System.out.println("Status code: " + status + ", Body: " +  method.getResponseBodyAsString());
    }
 
源代码14 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testRemoveParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
源代码15 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testGetParticipantsAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g1.getKey() + "/participants";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> participants = parseUserArray(body);
    assertNotNull(participants);
    assertEquals(participants.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : participants) {
        if (participant.getKey().equals(part1.getKey())) {
            idKey1 = part1.getKey();
        } else if (participant.getKey().equals(part2.getKey())) {
            idKey2 = part2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
源代码16 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testGetOwnersAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> owners = parseUserArray(body);
    assertNotNull(owners);
    assertEquals(owners.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : owners) {
        if (participant.getKey().equals(owner1.getKey())) {
            idKey1 = owner1.getKey();
        } else if (participant.getKey().equals(owner2.getKey())) {
            idKey2 = owner2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
源代码17 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testAddParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
源代码18 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testRemoveParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
源代码19 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testRemoveTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
源代码20 项目: davmail   文件: ExchangeDavMethod.java
/**
 * Get Multistatus responses.
 *
 * @return responses
 * @throws HttpException on error
 */
public MultiStatusResponse[] getResponses() throws HttpException {
    if (responses == null) {
        throw new HttpException(getStatusLine().toString());
    }
    return responses.toArray(new MultiStatusResponse[0]);
}
 
源代码21 项目: olat   文件: RepositoryEntriesITCase.java
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
            new StringPart("displayname", "QTI demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("QTI demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
源代码22 项目: davmail   文件: ExchangeDavMethod.java
/**
 * Return method http status code.
 *
 * @return http status code
 * @throws HttpException on error
 */
public int getResponseStatusCode() throws HttpException {
    String responseDescription = getResponse().getResponseDescription();
    if ("HTTP/1.1 201 Created".equals(responseDescription)) {
        return HttpStatus.SC_CREATED;
    } else {
        return HttpStatus.SC_OK;
    }
}
 
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException,
IOException, HttpException, URIException, JSONException
{
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER)
    {
        post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }
    StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8");
    post.setRequestEntity(requestEntity);
    try
    {
        httpClient.executeMethod(post);
        if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
        {
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null)
            {
                String redirectLocation = locationHeader.getValue();
                post.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(post);
            }
        }
        if (post.getStatusCode() != HttpServletResponse.SC_OK)
        {
            throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
        JSONObject json = new JSONObject(new JSONTokener(reader));
        return json;
    }
    finally
    {
        post.releaseConnection();
    }
}
 
源代码24 项目: alfresco-core   文件: AbstractHttpClient.java
protected long executeMethod(HttpMethod method) throws HttpException, IOException
{
    // execute method

    long startTime = System.currentTimeMillis();

    // TODO: Pool, and sent host configuration and state on execution
    getHttpClient().executeMethod(method);

    return System.currentTimeMillis() - startTime;
}
 
源代码25 项目: olat   文件: I18nITCase.java
@Test
public void testExecuteService() throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("i18n").path("org.olat.presentation").path("ok").build();
    final GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, false);
    final int code = getHttpClient().executeMethod(method);
    assertEquals(200, code);
    final String response = method.getResponseBodyAsString();
    assertEquals("OK", response);
}
 
源代码26 项目: olat   文件: OlatJerseyTestCase.java
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public HttpClient loginWithCookie(final String username, final String password) throws HttpException, IOException {
    final HttpClient c = getHttpClient();
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
    return c;
}
 
源代码27 项目: cosmic   文件: UriUtils.java
public static void checkUrlExistence(final String url) {
    if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) {
        final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
        final HeadMethod httphead = new HeadMethod(url);
        try {
            if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) {
                throw new IllegalArgumentException("Invalid URL: " + url);
            }
        } catch (final HttpException hte) {
            throw new IllegalArgumentException("Cannot reach URL: " + url);
        } catch (final IOException ioe) {
            throw new IllegalArgumentException("Cannot reach URL: " + url);
        }
    }
}
 
public static Map<String, String> getData(OsgiClient osgiClient, String bundleSymbolicName) throws OsgiClientException {
    Map<String, String> answer = new HashMap<>();
    RepositoryInfo repositoryInfo = getRepositoryInfo(osgiClient);
    GetMethod method = new GetMethod(repositoryInfo.appendPath("system/console/bundles/" + bundleSymbolicName + ".json"));
    HttpClient client = getHttpClient(osgiClient);

    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK) {
            throw new HttpException("Got status code " + result + " for call to " + method.getURI());
        }
        try ( InputStream input = method.getResponseBodyAsStream() ) {
            JSONObject object = new JSONObject(new JSONTokener(new InputStreamReader(input)));
            JSONArray bundleData = object.getJSONArray("data");
            if(bundleData.length() > 1) {
                throw new OsgiClientException("More than one Bundle found");
            } else {
                JSONObject bundle = bundleData.getJSONObject(0);
                for(Object item: bundle.keySet()) {
                    String name = item + "";
                    String value = bundle.get(name) + "";
                    answer.put(name, value);
                }
            }
        }
    } catch (IOException | JSONException e) {
        throw new OsgiClientException(e);
    } finally {
        method.releaseConnection();
    }
    return answer;
}
 
源代码29 项目: development   文件: RequestHandlerBase.java
/**
 * Will write the proxy specific headers such as Via and x-forwarded-for.
 * 
 * @param method Method to write the headers to
 * @param request The incoming request, will need to get virtual host.
 * @throws HttpException 
 */
private void setProxySpecificHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    String serverHostName = "jEasyExtensibleProxy";
    try {
        serverHostName = InetAddress.getLocalHost().getHostName();   
    } catch (UnknownHostException e) {
        log.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
    }
    
    String originalVia = request.getHeader("via");
    StringBuffer via = new StringBuffer("");
    if (originalVia != null) {
        if (originalVia.indexOf(serverHostName) != -1) {
            log.error("This proxy has already handled the request, will abort.");
            throw new HttpException("Request has a cyclic dependency on this proxy.");
        }
        via.append(originalVia).append(", ");
    }
    via.append(request.getProtocol()).append(" ").append(serverHostName);
     
    method.setRequestHeader("via", via.toString());
    method.setRequestHeader("x-forwarded-for", request.getRemoteAddr());     
    method.setRequestHeader("x-forwarded-host", request.getServerName());
    method.setRequestHeader("x-forwarded-server", serverHostName);
    
    method.setRequestHeader("accept-encoding", "");
}
 
源代码30 项目: development   文件: ProxyFilter.java
/**
 * Will create the method and execute it. After this the method is sent to a
 * ResponseHandler that is returned.
 * 
 * @param httpRequest
 *            Request we are receiving from the client
 * @param url
 *            The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException
 *             If the method specified by the request isn't handled
 * @throws IOException
 *             When there is a problem with the streams
 * @throws HttpException
 *             The httpclient can throw HttpExcetion when executing the
 *             method
 */
ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory
            .createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException(
                    "Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}
 
 类方法
 同包方法