当前位置: 首页>>代码示例>>Java>>正文


Java HttpEntity类代码示例

本文整理汇总了Java中org.apache.http.HttpEntity的典型用法代码示例。如果您正苦于以下问题:Java HttpEntity类的具体用法?Java HttpEntity怎么用?Java HttpEntity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpEntity类属于org.apache.http包,在下文中一共展示了HttpEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getRedirect

import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
 * get a redirect for an url: this method shall be called if it is expected that a url
 * is redirected to another url. This method then discovers the redirect.
 * @param urlstring
 * @param useAuthentication
 * @return the redirect url for the given urlstring
 * @throws IOException if the url is not redirected
 */
public static String getRedirect(String urlstring) throws IOException {
    HttpGet get = new HttpGet(urlstring);
    get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    CloseableHttpClient httpClient = getClosableHttpClient();
    HttpResponse httpResponse = httpClient.execute(get);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        if (httpResponse.getStatusLine().getStatusCode() == 301) {
            for (Header header: httpResponse.getAllHeaders()) {
                if (header.getName().equalsIgnoreCase("location")) {
                    EntityUtils.consumeQuietly(httpEntity);
                    return header.getValue();
                }
            }
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("redirect for  " + urlstring+ ": no location attribute found");
        } else {
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("no redirect for  " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        throw new IOException("client connection to " + urlstring + " fail: no connection");
    }
}
 
开发者ID:yacy,项目名称:yacy_grid_mcp,代码行数:34,代码来源:ClientConnection.java

示例2: getRequest

import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "https://samurai.sipgate.net/RPC2";
    HttpPost httpPost = new HttpPost(requestURL);
    // TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
    String userpassword = acc.username + ":" + acc.data;
    String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
    httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
    httpPost.addHeader("Content-Type", "text/xml");
    
    // prepare POST body
    String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";

    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
开发者ID:treasure-lau,项目名称:CSipSimple,代码行数:23,代码来源:Sipgate.java

示例3: postRecommendationReaction

import org.apache.http.HttpEntity; //导入依赖的package包/类
public static boolean postRecommendationReaction(@NotNull String lessonId, @NotNull String user, int reaction) {
  final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.RECOMMENDATION_REACTIONS_URL);
  final String json = new Gson()
    .toJson(new StepicWrappers.RecommendationReactionWrapper(new StepicWrappers.RecommendationReaction(reaction, user, lessonId)));
  post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
  final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
  if (client == null) return false;
  setTimeout(post);
  try {
    final CloseableHttpResponse execute = client.execute(post);
    final int statusCode = execute.getStatusLine().getStatusCode();
    final HttpEntity entity = execute.getEntity();
    final String entityString = EntityUtils.toString(entity);
    EntityUtils.consume(entity);
    if (statusCode == HttpStatus.SC_CREATED) {
      return true;
    }
    else {
      LOG.warn("Stepic returned non-201 status code: " + statusCode + " " + entityString);
      return false;
    }
  }
  catch (IOException e) {
    LOG.warn(e.getMessage());
    return false;
  }
}
 
开发者ID:medvector,项目名称:educational-plugin,代码行数:28,代码来源:EduAdaptiveStepicConnector.java

示例4: getRequest

import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "http://200.152.124.172/billing/webservice/Server.php";
    
    HttpPost httpPost = new HttpPost(requestURL);
    httpPost.addHeader("SOAPAction", "\"mostra_creditos\"");
    httpPost.addHeader("Content-Type", "text/xml");

    // prepare POST body
    String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " +
            "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
            "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" +
            "><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" +
            "<chave xsi:type=\"xsd:string\">" +
            acc.data +
            "</chave><username xsi:type=\"xsd:string\">" +
            acc.username.replaceAll("^12", "") +
            "</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", ""));
    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
开发者ID:treasure-lau,项目名称:CSipSimple,代码行数:28,代码来源:Mobex.java

示例5: getContentCharSet

import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:28,代码来源:EntityUtils.java

示例6: doDownload

import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
 * 通过httpClient get 下载文件
 *
 * @param url      网络文件全路径
 * @param savePath 保存文件全路径
 * @return 状态码 200表示成功
 */
public static int doDownload(String url, String savePath) {
	// 创建默认的HttpClient实例.
	CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
	HttpGet get = new HttpGet(url);
	CloseableHttpResponse closeableHttpResponse = null;
	try {
		closeableHttpResponse = closeableHttpClient.execute(get);
		HttpEntity entity = closeableHttpResponse.getEntity();
		if (entity != null) {
			InputStream in = entity.getContent();
			FileOutputStream out = new FileOutputStream(savePath);
			IOUtils.copy(in, out);
			EntityUtils.consume(entity);
			closeableHttpResponse.close();
		}
		int code = closeableHttpResponse.getStatusLine().getStatusCode();
		closeableHttpClient.close();
		return code;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		closeSource(closeableHttpClient, closeableHttpResponse);
	}
	return 0;
}
 
开发者ID:CharleyXu,项目名称:tulingchat,代码行数:33,代码来源:HttpClientUtil.java

示例7: useHttpClientPost

import org.apache.http.HttpEntity; //导入依赖的package包/类
private void useHttpClientPost(String url) {
    HttpPost mHttpPost = new HttpPost(url);
    mHttpPost.addHeader("Connection", "Keep-Alive");
    try {
        HttpClient mHttpClient = createHttpClient();
        List<NameValuePair> postParams = new ArrayList<>();
        //要传递的参数
        postParams.add(new BasicNameValuePair("ip", "59.108.54.37"));
        mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
        HttpEntity mHttpEntity = mHttpResponse.getEntity();
        int code = mHttpResponse.getStatusLine().getStatusCode();
        if (null != mHttpEntity) {
            InputStream mInputStream = mHttpEntity.getContent();
            String respose = converStreamToString(mInputStream);
            Log.d(TAG, "请求状态码:" + code + "\n请求结果:\n" + respose);
            mInputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
开发者ID:henrymorgen,项目名称:android-advanced-light,代码行数:23,代码来源:MainActivity.java

示例8: deployApp

import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
 * Sets the app to active state
 *
 * @param customerName
 *        the name of the customer
 * @param appName
 *        the name of the app
 * @return request object to check status codes and return values
 */
public Response deployApp( String customerName, String appName )
{
	HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
	setAuthorizationHeader( request );
	request.addHeader( "ContentType", "application/json" );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	try
	{
		final HttpEntity requestEntity = new StringEntity(
			"{\"applicationStatus\":{\"" + this.system + "\":\"ACTIVE\"}, \"applicationName\":\"" +
				appName + "\"}",
			ContentType.APPLICATION_JSON );
		request.setEntity( requestEntity );

		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
开发者ID:ApinautenGmbH,项目名称:integration-test-helper,代码行数:33,代码来源:AomHttpClient.java

示例9: process

import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public void process(final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
    final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
            .withMethod(request.getRequestLine().getMethod());

    Stream.of(request.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        entity.writeTo(os);

        final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
        builder.withBody(body);
    }

    final HttpRequestAttachment requestAttachment = builder.build();
    processor.addAttachment(requestAttachment, renderer);
}
 
开发者ID:allure-framework,项目名称:allure-java,代码行数:23,代码来源:AllureHttpClientRequest.java

示例10: extractFromResponse

import org.apache.http.HttpEntity; //导入依赖的package包/类
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
    RestHeartClientResponse response = null;
    JsonObject responseObj = null;
    if (httpResponse != null) {
        StatusLine statusLine = httpResponse.getStatusLine();
        Header[] allHeaders = httpResponse.getAllHeaders();
        HttpEntity resEntity = httpResponse.getEntity();
        if (resEntity != null) {
            try {
                String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
                if (responseStr != null && !responseStr.isEmpty()) {
                    JsonParser parser = new JsonParser();
                    responseObj = parser.parse(responseStr).getAsJsonObject();
                }
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
            }
        }

        response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
    }
    return response;
}
 
开发者ID:SoftGorilla,项目名称:restheart-java-client,代码行数:24,代码来源:RestHeartClientApi.java

示例11: Request

import org.apache.http.HttpEntity; //导入依赖的package包/类
public Request(String id,
               String method,
               String url,
               ResponseType responseType,
               Map<String, String> headers,
               Map<String, String> parameters,
               HttpEntity entity,
               Map<String, String> extras) {
    this.id = StringUtils.isNotBlank(id) ? id : SpiderStrUtils.getUUID();
    this.method = StringUtils.isNotBlank(method) ? method : Request.METHOD_GET;
    this.url = url;
    this.responseType = responseType != null ? responseType : ResponseType.TEXT;
    this.headers = headers;
    this.parameters = parameters;
    this.entity = entity;
    this.extras = extras;
}
 
开发者ID:brucezee,项目名称:jspider,代码行数:18,代码来源:Request.java

示例12: parseResponse

import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public ReadAggregateGroupResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ReadAggregateGroupResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:23,代码来源:ReadAggregateGroupParser.java

示例13: parseResponse

import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public PyroclastConsumer parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            SubscribeToTopicResult result = mapper.readValue(json, SubscribeToTopicResult.class);

            if (result.getSuccess()) {
                return new PyroclastConsumer(topicId, readApiKey, format, endpoint, subscriptionName);
            } else {
                throw new UnknownAPIException(result.getFailureReason());
            }

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:27,代码来源:SubscribeToTopicParser.java

示例14: updateConfig

import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
 * Updates a modules config for the given app
 *
 * @param customerName
 *        the name of the customer
 * @param appName
 *        the name of the app
 * @param moduleName
 *        the name of the module to update config for
 * @param key
 *        config key
 * @param value
 *        value of the config
 * @return request object to check status codes and return values
 */
public Response updateConfig( String customerName, String appName, String moduleName, String key,
	String value )
{
	final HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
	setAuthorizationHeader( request );
	request.addHeader( "ContentType", "application/json" );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	try
	{
		final HttpEntity requestEntity = new StringEntity(
			"{\"configuration\":" + "	{\"" + this.system.toString( ).toLowerCase( ) + "Config\": {\"" +
				moduleName + "\":{\"" + key + "\":\"" + value + "\"}}}, \"applicationName\":\"" + appName + "\"}",
			ContentType.APPLICATION_JSON );
		request.setEntity( requestEntity );

		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
开发者ID:ApinautenGmbH,项目名称:integration-test-helper,代码行数:40,代码来源:AomHttpClient.java

示例15: createIndex

import org.apache.http.HttpEntity; //导入依赖的package包/类
private void createIndex() {
  Response response;

  try (InputStream payload = FactSearchManager.class.getClassLoader().getResourceAsStream(MAPPINGS_JSON)) {
    // Need to use low-level client here because the Index API is not yet supported by the high-level client.
    HttpEntity body = new InputStreamEntity(payload, ContentType.APPLICATION_JSON);
    response = clientFactory.getLowLevelClient().performRequest("PUT", INDEX_NAME, Collections.emptyMap(), body);
  } catch (IOException ex) {
    throw logAndExit(ex, "Could not perform request to create index.");
  }

  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    String msg = String.format("Could not create index '%s'.", INDEX_NAME);
    LOGGER.error(msg);
    throw new IllegalStateException(msg);
  }

  LOGGER.info("Successfully created index '%s'.", INDEX_NAME);
}
 
开发者ID:mnemonic-no,项目名称:act-platform,代码行数:20,代码来源:FactSearchManager.java


注:本文中的org.apache.http.HttpEntity类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。