Java 类org.apache.http.client.ClientProtocolException 实例源码

项目:qonduit    文件:HTTPStrictTransportSecurityIT.java   
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
项目:cloud-ariba-partner-flow-extension-ext    文件:OpenApisEndpoint.java   
/**
 * Performs HTTP Post request with OAuth authentication for the endpoint
 * with the given path, with the given JSON as payload and the given HTTP
 * headers.
 * 
 * @param path
 *            the path to be called.
 * @param headers
 *            map with HTTP header names and values to be included in the
 *            request.
 * @param jsonContent
 *            the JSON content to be posted.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
CloseableHttpResponse executeHttpPost(String path, Map<String, String> headers, String jsonContent)
        throws ClientProtocolException, IOException {
    logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);

    HttpPost httpPost = createHttpPost(baseUri + path);

    if (headers != null) {
        for (String header : headers.keySet()) {
            httpPost.addHeader(header, headers.get(header));
        }
    }

    if (jsonContent != null) {
        StringEntity input = new StringEntity(jsonContent);
        input.setContentType(MediaType.APPLICATION_JSON);
        httpPost.setEntity(input);
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
    return response;
}
项目:neo-java    文件:TestBlockSerialization.java   
/**
 * pulls all the blocks (slow) to check for full coverage.
 *
 * @throws ClientProtocolException
 *             if an error occurs.
 * @throws IOException
 *             if an error occurs.
 * @throws DecoderException
 *             if an error occurs.
 * @throws InterruptedException
 *             if an error occurs.
 */
@Test
@Ignore
public void test00ZAllBlocks() throws ClientProtocolException, IOException, DecoderException, InterruptedException {
    final BlockDb blockDb = new AbstractJsonMockBlockDb() {
        @Override
        public JSONArray getMockBlockDb() {
            return new JSONArray();
        }
    };
    final long maxBlockIx = blockDb.getHeaderOfBlockWithMaxIndex().getIndexAsLong();

    final Set<TransactionType> knownTypeSet = new TreeSet<>();

    for (long blockIx = 0; blockIx <= maxBlockIx; blockIx++) {
        final Block block = blockDb.getFullBlockFromHeight(blockIx);
        for (int txIx = 0; txIx < block.getTransactionList().size(); txIx++) {
            final Transaction tx = block.getTransactionList().get(txIx);
            if (!knownTypeSet.contains(tx.type)) {
                LOG.error("getBlock {} {} tx {} {}", block.getIndexAsLong(), block.prevHash, txIx, tx.type);
                knownTypeSet.add(tx.type);
            }
        }
    }
    blockDb.close();
}
项目:letv    文件:HttpEngine.java   
private HttpEngine() {
    this.mDefaultHttpClient = null;
    this.mDefaultHttpClient = createHttpClient();
    this.mDefaultHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (DataStatistics.getInstance().isDebug()) {
                Log.d(DataStatistics.TAG, exception.getClass() + NetworkUtils.DELIMITER_COLON + exception.getMessage() + ",executionCount:" + executionCount);
            }
            if (executionCount >= 3) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof ClientProtocolException) {
                return true;
            }
            return false;
        }
    });
}
项目:kafka-connect-marklogic    文件:TestMarkLogicSincTask.java   
@Test
public void shouldPut() throws ClientProtocolException, IOException, URISyntaxException{

    List<SinkRecord> documents = new ArrayList<SinkRecord>();
    final Account account = new Account("A1");
    final Client client = new Client("C1", account);
    final QuoteRequest quoteRequest = new QuoteRequest("Q1", "APPL", 100, client, new Date());

    documents.add(new SinkRecord("trades", 1, null, null, null,  MAPPER.convertValue(quoteRequest, Map.class), 0));
    markLogicSinkTask.put(documents);

       final HttpResponse response = super.get("/C1/A1/Q1.json");
       final QuoteRequest qr = MAPPER.readValue(response.getEntity().getContent(), QuoteRequest.class);
       assertEquals("APPL", qr.getSymbol());
       super.delete("/C1/A1/Q1.json");
}
项目:kafka-connect-marklogic    文件:TestMarkLogicBufferedWriter.java   
@Test
public void shouldWrite() throws ClientProtocolException, IOException, URISyntaxException{

    final List<SinkRecord> documents = new ArrayList<SinkRecord>();
    final QuoteRequest quoteRequest1 = new QuoteRequest("Q2", "IBM", 100, new Client("C2", new Account("A2")), new Date());
    final QuoteRequest quoteRequest2 = new QuoteRequest("Q3", "GS", 100, new Client("C3", new Account("A3")), new Date());

    documents.add(new SinkRecord("topic", 1, null, null, null, MAPPER.convertValue(quoteRequest1, Map.class), 0));
    documents.add(new SinkRecord("topic", 1, null, null, null, MAPPER.convertValue(quoteRequest2, Map.class), 0));
    writer.write(documents);

    HttpResponse response = super.get("/C2/A2/Q2.json");
    QuoteRequest qr = MAPPER.readValue(response.getEntity().getContent(), QuoteRequest.class);
    assertEquals("IBM", qr.getSymbol());
    response = super.get("/C3/A3/Q3.json");
    qr = MAPPER.readValue(response.getEntity().getContent(), QuoteRequest.class);
    assertEquals("GS", qr.getSymbol());
    super.delete("/C3/A3/Q3.json");
    super.delete("/C2/A2/Q2.json");
}
项目:weixin_api    文件:MpUserApi.java   
/**
 * 删除标签
 * 
 * @param id
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public BaseResp apiTagsDelete(int id)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/tags/delete?access_token=%s", token.getAccessToken());
    TreeMap<String, Object> tag = new TreeMap<String, Object>();
    tag.put("id", id);

    TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
    reqMap.put("tag", tag);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    BaseResp resp = new Gson().fromJson(respText, BaseResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiTagsDelete %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:weixin_api    文件:MpUserApi.java   
/**
 * 批量为用户打标签
 * 
 * @param tagid
 * @param openids
 *            每次传入的openid列表个数不能超过50个
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public BaseResp apiTagsMembersBatchTagging(int tagid, String[] openids)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/tags/members/batchtagging?access_token=%s", token.getAccessToken());
    TreeMap<String, Object> tag = new TreeMap<String, Object>();
    tag.put("tagid", tagid);
    tag.put("openid_list", openids);

    TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
    reqMap.put("tag", tag);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    BaseResp resp = new Gson().fromJson(respText, BaseResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiTagsMembersBatchTagging %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:instagram4j    文件:Instagram4j.java   
/**
 * Send request to endpoint
 * @param request Request object
 * @return success flag
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public <T> T sendRequest(InstagramRequest<T> request) throws ClientProtocolException, IOException {

    log.info("Sending request: " + request.getClass().getName());

    if (!this.isLoggedIn
            && request.requiresLogin()) {
        throw new IllegalStateException("Need to login first!");
    }

    // wait to simulate real human interaction
    randomWait();

    request.setApi(this);
    T response = request.execute();

    log.debug("Result for " + request.getClass().getName() + ": " + response);

    return response;
}
项目:financisto1-holo    文件:FlowzrSyncEngine.java   
public static void requery(String tableName,Class clazz,String key) throws ClientProtocolException, IOException, JSONException,Exception {
    Log.i(TAG,"Got key " + key + " but couldn't find related parent tr, requerying ...");
    String url=FLOWZR_API_URL + nsString + "/key/?tableName=" + DatabaseHelper.TRANSACTION_TABLE + "&key=" + key;                   
    StringBuilder builder = new StringBuilder();        
    DefaultHttpClient http_client2= new DefaultHttpClient();
    http_client2.setCookieStore(http_client.getCookieStore());
    HttpGet httpGet = new HttpGet(url);
    HttpResponse httpResponse = http_client2.execute(httpGet);
       HttpEntity httpEntity = httpResponse.getEntity();
       InputStream content = httpEntity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(content));
       String line;
       while ((line = reader.readLine()) != null) {
         builder.append(line);
       }
    JSONObject o = new JSONObject(builder.toString()).getJSONArray(DatabaseHelper.TRANSACTION_TABLE).getJSONObject(0);
    saveEntityFromJson(o, tableName, clazz,1);
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException {

        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(host, 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        String  body = "{\"default-user\": \""+usr+"\"}";

        HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default");
        put.addHeader("Content-type", "application/json");
        put.setEntity(new StringEntity(body));

        HttpResponse response2 = client.execute(put);
        HttpEntity respEntity = response2.getEntity();
        if(respEntity != null){
            String content =  EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    }
项目:RoboInsta    文件:InstagramGetRequest.java   
@Override
public T execute() throws ClientProtocolException, IOException {
    HttpGet get = new HttpGet(InstagramConstants.apiUrl + getUrl());
    get.addHeader("Connection", "close");
    get.addHeader("Accept", "*/*");
    get.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    get.addHeader("Cookie2", "$Version=1");
    get.addHeader("Accept-Language", "en-US");
    get.addHeader("User-Agent", InstagramConstants.userAgent);

    HttpResponse response = InstagramContextHolder.getContext().getHttpClient().execute(get);

    int resultCode = response.getStatusLine().getStatusCode();
    String content = EntityUtils.toString(response.getEntity());

    get.releaseConnection();

    return parseResult(resultCode, content);
}
项目:weixin_api    文件:MpApi.java   
/**
 * 创建临时二维码
 * 
 * @param seconds
 *            该二维码有效时间,以秒为单位。 最大不超过2592000(即30天)此字段如果不填,则默认有效期为30秒。
 * @param sceneId
 *            场景值ID,临时二维码时为32bit非0整型
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public QrcodeCreateResp apiQrcodeCreateTemp(Integer seconds, int sceneId)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = apiToken();
    String path = String.format("/qrcode/create?access_token=%s", token.getAccessToken());

    TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
    reqMap.put("expire_seconds", seconds);
    reqMap.put("action_name", "QR_SCENE");
    TreeMap<String, Object> actionInfo = new TreeMap<String, Object>();
    TreeMap<String, Object> scene = new TreeMap<String, Object>();
    scene.put("scene_id", sceneId);
    actionInfo.put("scene", scene);
    reqMap.put("action_info", actionInfo);

    String respText = HttpUtil.post(config.getApiHttps(), path, reqMap);
    QrcodeCreateResp resp = new Gson().fromJson(respText, QrcodeCreateResp.class);
    if (log.isInfoEnabled()) {
        log.info(String.format("apiQrcodeCreateTemp %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:kowalski    文件:Dependent.java   
public Page<URI, Artifact> fetchPage(URI uri)
        throws ClientProtocolException, IOException, URISyntaxException, ParseException, NotOkResponseException {
    HttpGet request = new HttpGet(uri);
    try (CloseableHttpResponse response = this.client.execute(request)) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return new Page<>(Optional.empty(), Collections.emptyList());
        }
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new NotOkResponseException(
                    String.format("Service response not ok %s %s %s", response.getStatusLine(),
                            response.getAllHeaders(), EntityUtils.toString(response.getEntity())));
        }
        Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()), uri.toString());
        Optional<URI> next = Optional.empty();
        Elements nexts = document.select(".search-nav li:last-child a[href]");
        if (!nexts.isEmpty()) {
            next = Optional.of(new URI(nexts.first().attr("abs:href")));
        }
        List<Artifact> artifacts = document.select(".im .im-subtitle").stream()
                .map(element -> new DefaultArtifact(element.select("a:nth-child(1)").first().text(),
                        element.select("a:nth-child(2)").first().text(), null, null))
                .collect(Collectors.toList());
        return new Page<>(next, artifacts);
    }
}
项目:aws-xray-sdk-java    文件:DefaultHttpClient.java   
@Override
public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
    Subsegment subsegment = getRecorder().beginSubsegment(TracedHttpClient.determineTarget(request).getHostName());
    try {
        if (null != subsegment) {
            TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
        }
        CloseableHttpResponse response = super.execute(request, context);
        if (null != subsegment) {
            TracedResponseHandler.addResponseInformation(subsegment, response);
        }
        return response;
    } catch (Exception e) {
        if (null != subsegment) {
            subsegment.addException(e);
        }
        throw e;
    } finally {
        if (null != subsegment) {
            getRecorder().endSubsegment();
        }
    }
}
项目:cloud-ariba-partner-flow-extension-ext    文件:OpenApisEndpoint.java   
/**
 * Performs HTTP Get request with OAuth authentication for the endpoint with
 * the given path with the given HTTP headers.
 * 
 * @param path
 *            the path to be called.
 * @param headers
 *            map with HTTP header names and values to be included in the
 *            request.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
CloseableHttpResponse executeHttpGet(String path, Map<String, String> headers)
        throws ClientProtocolException, IOException {
    logger.debug(DEBUG_EXECUTING_HTTP_GET_FOR, baseUri, path);

    HttpGet httpGet = createHttpGet(baseUri + path);
    for (String header : headers.keySet()) {
        httpGet.addHeader(header, headers.get(header));
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpGet);

    logger.debug(DEBUG_EXECUTED_HTTP_GET_FOR, baseUri, path);
    return response;
}
项目:TinyURL    文件:TinyURLServiceTest.java   
@Test
public void testGetURL() throws ClientProtocolException, IOException {
    String shortURL = "ba";
    HttpUriRequest request = new HttpGet("http://localhost:8080/TinyURL/details/" + shortURL);
    HttpResponse response = HttpClientBuilder.create().build().execute(request);

    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    //fail("Not yet implemented");
}
项目:cloud-ariba-partner-flow-extension-ext    文件:OpenApisEndpoint.java   
/**
 * Performs HTTP Post request with OAuth authentication for the endpoint
 * with the given path, with the given binary bodies as payload. Uses
 * multipart/mixed content type.
 * 
 * @param path
 *            the path to be called.
 * @param binaryBodies
 *            the payload.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
CloseableHttpResponse executeHttpPost(String path, List<BinaryBody> binaryBodies)
        throws ClientProtocolException, IOException {
    logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);

    HttpPost httpPost = createHttpPost(baseUri + path);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MULTIPART_MIXED_BOUNDARY);

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (BinaryBody binaryBody : binaryBodies) {
        multipartEntityBuilder.addBinaryBody(binaryBody.getBinaryBodyName(), binaryBody.getFileStream(),
                ContentType.create(binaryBody.getMediaType()), binaryBody.getFileName());
    }

    HttpEntity httpEntity = multipartEntityBuilder.setBoundary(OpenApisEndpoint.BOUNDARY).build();
    httpPost.setEntity(httpEntity);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);
    return response;
}
项目:weixin_api    文件:MpMsgApi.java   
/**
 * 发送模板消息。 在模版消息发送任务完成后,有事件TEMPLATESENDJOBFINISH通知。
 * 
 * @param touser
 * @param templateId
 * @param url
 * @param data
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public MessageTemplateSendResp apiMessageTemplateSend(String touser, String templateId, String url, String data)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/message/template/send?access_token=%s", token.getAccessToken());
    TreeMap<String, String> reqMap = new TreeMap<String, String>();
    reqMap.put("touser", touser);
    reqMap.put("template_id", templateId);
    reqMap.put("url", url);
    reqMap.put("data", data);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);

    MessageTemplateSendResp resp = new Gson().fromJson(respText, MessageTemplateSendResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiMessageTemplateSend %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:weixin_api    文件:MpMsgApi.java   
/**
 * 设置所属行业。每月可修改行业1次,账号仅可使用所属行业中相关的模板
 * 
 * @param industryId1
 * @param industryId2
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public BaseResp apiTemplateApiSetIndustry(String industryId1, String industryId2)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/template/api_set_industry?access_token=%s", token.getAccessToken());

    TreeMap<String, String> reqMap = new TreeMap<String, String>();
    reqMap.put("industry_id1", industryId1);
    reqMap.put("industryId2", industryId2);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    BaseResp resp = new Gson().fromJson(respText, BaseResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiTemplateApiSetIndustry %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:weixin_api    文件:MpMaterialApi.java   
/**
 * 上传图文消息素材
 * 
 * @param articles
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public MediaUploadResp apiMediaUploadNews(Article[] articles)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/media/uploadnews?access_token=%s", token.getAccessToken());

    TreeMap<String, Article[]> reqMap = new TreeMap<String, Article[]>();
    reqMap.put("articles", articles);

    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    MediaUploadResp resp = new Gson().fromJson(respText, MediaUploadResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiMediaUploadNews %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:weixin_api    文件:MpMaterialApi.java   
/**
 * 视频素材上传为群发素材
 * 
 * @param mediaId
 * @param title
 * @param description
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public MediaUploadResp apiMediaUploadVideo(String mediaId, String title, String description)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/media/uploadvideo?access_token=%s", token.getAccessToken());

    TreeMap<String, String> reqMap = new TreeMap<String, String>();
    reqMap.put("media_id", mediaId);
    reqMap.put("title", title);
    reqMap.put("description", description);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    MediaUploadResp resp = new Gson().fromJson(respText, MediaUploadResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiMediaUploadVideo %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:RobotServer    文件:HttpService.java   
private String httpPost(String postUrl, String postData, String contentType) throws ClientProtocolException,
        IOException {
    CloseableHttpResponse response = null;
    try {
        HttpPost post = new HttpPost(postUrl);
        StringEntity entity = new StringEntity(postData, UTF8);
        entity.setContentType(contentType);
        post.setEntity(entity);
        response = getHttpClient().execute(post);
        return EntityUtils.toString(response.getEntity(), UTF8);
    } finally {
        if (null != response) {
            response.close();
        }
    }
}
项目:aws-xray-sdk-java    文件:DefaultHttpClient.java   
@Override
public CloseableHttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException {
    Subsegment subsegment = getRecorder().beginSubsegment(target.getHostName());
    try {
        if (null != subsegment) {
            TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
        }
        CloseableHttpResponse response = super.execute(target, request);
        if (null != subsegment) {
            TracedResponseHandler.addResponseInformation(subsegment, response);
        }
        return response;
    } catch (Exception e) {
        if (null != subsegment) {
            subsegment.addException(e);
        }
        throw e;
    } finally {
        if (null != subsegment) {
            getRecorder().endSubsegment();
        }
    }
}
项目:sjk    文件:CatalogConvertorControllerTest.java   
@Test
public void testEditList() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.list.d";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1,2");
    urlb.setParameter("marketName", "eoemarket,eoemarket");
    urlb.setParameter("catalog", "1,1");
    urlb.setParameter("subCatalog", "15,8");
    urlb.setParameter("subCatalogName", "系统工具,生活娱乐1");
    urlb.setParameter("targetCatalog", "1,1");
    urlb.setParameter("targetSubCatalog", "14,9");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:weixin_api    文件:MpCustomServiceApi.java   
/**
 * 关闭会话
 * 
 * @param account
 * @param openid
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public BaseResp apiCustomServiceKfSessionClose(String account, String openid)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/customservice/kfsession/close?access_token=%s", token.getAccessToken());
    // 构建请求参数进行获取
    TreeMap<String, String> reqMap = new TreeMap<String, String>();
    reqMap.put("kf_account", account);
    reqMap.put("openid", openid);

    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    BaseResp resp = new Gson().fromJson(respText, BaseResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiCustomServiceKfSessionCreate %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:weixin_api    文件:OpenApi.java   
/**
 * 获取公众号的选项设置信息集。
 * 
 * @param mpAppid
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws ClientProtocolException
 * @throws AccessTokenFailException
 */
public AuthorizerOption[] apiGetAuthorizerOptions(String mpAppid)
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
    // 检查MpAccessToken是否存在
    AuthorizerAccessToken authToken = runtime.getMpAuthorizerToken(mpAppid);
    if (authToken == null) {
        throw new IllegalStateException("无法获取公众号选项设置信息,因为MpAccessToken不存在");
    }

    AuthorizerOptionEnum[] optionDefines = AuthorizerOptionEnum.values();
    int length = optionDefines.length;
    AuthorizerOption[] authOptions = new AuthorizerOption[length];
    for (int idx = 0; idx < length; idx++) {
        AuthorizerOption authOption = apiGetAuthorizerOption(mpAppid, optionDefines[idx]);
        authOptions[idx] = authOption;
    }

    return authOptions;
}
项目:weixin_api    文件:OpenApi.java   
/**
 * 第三方平台对其所有API调用次数清零。每个月10次。
 * 
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws ClientProtocolException
 * @throws AccessTokenFailException
 */
public BaseResp apiClearQuota()
        throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {

    // 构建请求参数进行获取
    TreeMap<String, String> reqMsg = new TreeMap<String, String>();
    reqMsg.put("component_appid", config.getComponentAppid());

    ComponentAccessToken token = apiComponentToken();
    String path = String.format("/component/clear_quota?component_access_token=%s",
            token.getComponentAccessToken());

    String respText = HttpUtil.post(config.getApiHttps(), path, reqMsg);
    BaseResp resp = new Gson().fromJson(respText, BaseResp.class);
    if (log.isInfoEnabled()) {
        log.info(String.format("apiClearQuota %s", resp));
    }
    return resp;
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_null_since_httpClient_execute_returned_with_unknown_response_code()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(600);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertNull(response);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
项目:cloud-ariba-discovery-rfx-to-external-marketplace-ext    文件:OpenApisEndpoint.java   
/**
 * Performs HTTP Post request for the end point with the given path.
 * 
 * @param path
 *            the path to be called.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
public CloseableHttpResponse executeHttpPost(String path) throws ClientProtocolException, IOException {
    logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR, baseUri, path);

    HttpPost httpPost = createHttpPost(baseUri + path);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR, baseUri, path);
    return response;
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet")
public void doGet_should_throw_stockexception_since_httpClient_execute_returned_with_internal_server_error()
        throws ClientProtocolException, IOException {

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(500);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    try {
        HttpUtils.doGet("http://example.com", null);

        Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(),
                "API returned with Server Error");
        Assert.assertEquals(e.getCode(), 500);
    }
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet", expectedExceptions = StockException.class)
public void doGet_should_throw_stockexception_since_entityutils_tostring_throws_exception()
        throws ClientProtocolException, IOException, StockException {

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(400);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(null);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    HttpUtils.doGet("http://example.com", null);
}
项目:sjk    文件:MarketControllerTest.java   
@Test
public void testListMarkert() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/market/list.json";
    URIBuilder urlb = new URIBuilder(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(urlb.build());
    HttpResponse response = httpClient.execute(httpget);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doPost")
public void doPost_should_throw_stockexception_since_httpClient_execute_returned_with_bad_request()
        throws ClientProtocolException, IOException {

    String errorResponse = "{ \"error\": { \"message\": \"Test Response\" } }";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(errorResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(400);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    try {
        HttpUtils.doPost("http://example.com", null,
                errorResponse.getBytes(), ContentType.TEXT_PLAIN);

        Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(), errorResponse);
        Assert.assertEquals(e.getCode(), 400);
    }
}
项目:RoboInsta    文件:InstagramOperations.java   
public <T> T sendRequest(InstagramRequest<T> request) throws ClientProtocolException, IOException {
    if (!InstagramSecurityUtils.isLoggedIn()
        && request.requiresLogin()) {
        throw new IllegalStateException("Need to login first!");
    }
    return request.execute();
}
项目:RoboInsta    文件:OldInstagram.java   
public <T> T sendRequest(InstagramRequest<T> request) throws ClientProtocolException, IOException {
    if (!this.isLoggedIn
        && request.requiresLogin()) {
        throw new IllegalStateException("Need to login first!");
    }
    return request.execute();
}
项目:nbawrapper-stats    文件:QueryManager.java   
public static HttpResponse getHttpResponse(String url) throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("accept", "application/json");
    HttpResponse response = httpClient.execute(getRequest);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }
    return response;
}
项目:wechat-api-java    文件:HttpRequestUtil.java   
private static ResponseHandler<String> getStringResponseHandler() {
    return response -> {
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity, "UTF-8") : null;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    };
}
项目:bootstrap    文件:ValidationJSonIT.java   
private void testInvalidFormat(final String property,final String type) throws IOException, ClientProtocolException, JsonParseException, JsonMappingException {
    final HttpPost httppost = new HttpPost(BASE_URI + RESOURCE);
    httppost.setEntity(new StringEntity("{\"name\":\"" + "Junit2\",\""+property+"\":\"A\"}", ContentType.APPLICATION_JSON));
    httppost.setHeader(ACCEPT_LANGUAGE, "EN");
    final HttpResponse response = httpclient.execute(httppost);
    try {
        Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
        final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
        Assert.assertNotNull(content);
        @SuppressWarnings("all")
        final Map<String, Map<String, List<Map<String, Object>>>> result = (Map<String, Map<String, List<Map<String, Object>>>>) new ObjectMapperTrim()
                .readValue(content, HashMap.class);
        Assert.assertFalse(result.isEmpty());
        final Map<String, List<Map<String, Object>>> errors = result.get("errors");
        Assert.assertNotNull(errors);
        Assert.assertEquals(1, errors.size());
        final List<Map<String, Object>> errorsOnYear = errors.get(property);
        Assert.assertNotNull(errorsOnYear);
        Assert.assertEquals(1, errorsOnYear.size());

        final Map<String, Object> errorOnYear = errorsOnYear.get(0);
        Assert.assertEquals(type, errorOnYear.get(RULE));
        Assert.assertNull(errorOnYear.get(PARAMETERS2));
    } finally {
        response.getEntity().getContent().close();
    }
}
项目:car-bjpermit    文件:HttpClientUtils.java   
/**
 * get
 *
 * @param url     请求的url
 * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
 * @return
 * @throws IOException
 */
public String get(String url, Map<String, String> queries) throws IOException {
    String responseBody = "";
    //支持https
    CloseableHttpClient httpClient = getHttpClient();

    StringBuilder sb = new StringBuilder(url);

    appendQueryParams(queries, sb);

    HttpGet httpGet = new HttpGet(sb.toString());
    if (SetTimeOut) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SocketTimeout)
                .setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间
        httpGet.setConfig(requestConfig);
    }
    try {
        logger.info("Executing request " + httpGet.getRequestLine());
        //请求数据
        CloseableHttpResponse response = httpClient.execute(httpGet);
        logger.info(String.valueOf(response.getStatusLine()));
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            responseBody = EntityUtils.toString(entity);
        } else {
            logger.info("http return status error:" + status);
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        httpClient.close();
    }
    return responseBody;
}