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


Java ClientProtocolException类代码示例

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


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

示例1: setDefaultUser

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
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);
		}
	}
 
开发者ID:marklogic,项目名称:marklogic-rdf4j,代码行数:21,代码来源:ConnectedRESTQA.java

示例2: apiTagsDelete

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
/**
 * 删除标签
 * 
 * @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;
}
 
开发者ID:AlexLee-CN,项目名称:weixin_api,代码行数:27,代码来源:MpUserApi.java

示例3: sendRequest

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:brunocvcunha,项目名称:instagram4j,代码行数:27,代码来源:Instagram4j.java

示例4: requery

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
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);
}
 
开发者ID:tiberiusteng,项目名称:financisto1-holo,代码行数:19,代码来源:FlowzrSyncEngine.java

示例5: testHttpRequestGet

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
@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);

}
 
开发者ID:NationalSecurityAgency,项目名称:qonduit,代码行数:37,代码来源:HTTPStrictTransportSecurityIT.java

示例6: testGetURL

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
@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");
}
 
开发者ID:pawankumbhare4213,项目名称:TinyURL,代码行数:12,代码来源:TinyURLServiceTest.java

示例7: executeHttpPost

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:SAP,项目名称:cloud-ariba-partner-flow-extension-ext,代码行数:41,代码来源:OpenApisEndpoint.java

示例8: test00ZAllBlocks

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:coranos,项目名称:neo-java,代码行数:38,代码来源:TestBlockSerialization.java

示例9: HttpEngine

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
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;
        }
    });
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:22,代码来源:HttpEngine.java

示例10: shouldPut

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
@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");
}
 
开发者ID:sanjuthomas,项目名称:kafka-connect-marklogic,代码行数:17,代码来源:TestMarkLogicSincTask.java

示例11: shouldWrite

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
@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");
}
 
开发者ID:sanjuthomas,项目名称:kafka-connect-marklogic,代码行数:21,代码来源:TestMarkLogicBufferedWriter.java

示例12: apiTagsMembersBatchTagging

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
/**
 * 批量为用户打标签
 * 
 * @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;
}
 
开发者ID:AlexLee-CN,项目名称:weixin_api,代码行数:30,代码来源:MpUserApi.java

示例13: execute

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
@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);
}
 
开发者ID:Cinderpup,项目名称:RoboInsta,代码行数:20,代码来源:InstagramGetRequest.java

示例14: apiQrcodeCreateTemp

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
/**
 * 创建临时二维码
 * 
 * @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;
}
 
开发者ID:AlexLee-CN,项目名称:weixin_api,代码行数:35,代码来源:MpApi.java

示例15: fetchPage

import org.apache.http.client.ClientProtocolException; //导入依赖的package包/类
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);
	}
}
 
开发者ID:maenu,项目名称:kowalski,代码行数:26,代码来源:Dependent.java


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