Java Code Examples for org.apache.http.client.ClientProtocolException

The following examples show how to use org.apache.http.client.ClientProtocolException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cloud-odata-java   Source File: TestIssue105.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void checkContextForDifferentHostNamesRequests() throws ClientProtocolException, IOException, ODataException, URISyntaxException {
  URI uri1 = URI.create(getEndpoint().toString() + "$metadata");

  HttpGet get1 = new HttpGet(uri1);
  HttpResponse response1 = getHttpClient().execute(get1);
  assertNotNull(response1);

  URI serviceRoot1 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
  assertEquals(uri1.getHost(), serviceRoot1.getHost());

  get1.reset();

  URI uri2 = new URI(uri1.getScheme(), uri1.getUserInfo(), "127.0.0.1", uri1.getPort(), uri1.getPath(), uri1.getQuery(), uri1.getFragment());

  HttpGet get2 = new HttpGet(uri2);
  HttpResponse response2 = getHttpClient().execute(get2);
  assertNotNull(response2);

  URI serviceRoot2 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
  assertEquals(uri2.getHost(), serviceRoot2.getHost());
}
 
Example 2
Source Project: customer-review-crawler   Source File: Item.java    License: The Unlicense 6 votes vote down vote up
/**
 * @return the RAW XML document of ItemLookup (Large Response) from Amazon
 *         product advertisement API
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws ClientProtocolException
 * @throws IOException
 */
public String getXMLLargeResponse() throws InvalidKeyException,
		NoSuchAlgorithmException, ClientProtocolException, IOException {
	String responseBody = "";
	String signedurl = signInput();
	try {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(signedurl);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		responseBody = httpclient.execute(httpget, responseHandler);
		// responseBody now contains the contents of the page
		// System.out.println(responseBody);
		httpclient.getConnectionManager().shutdown();
	} catch (Exception e) {
		System.out.println("Exception" + " " + itemID + " " + e.getClass());
	}
	return responseBody;
}
 
Example 3
Source Project: YiBo   Source File: FanfouResponseHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
	public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		StatusLine statusLine = response.getStatusLine();
		HttpEntity entity = response.getEntity();
		String responseString = (entity == null ? null : EntityUtils.toString(entity));

		
		logger.debug("FanfouResponseHandler : {}", responseString);

		if (statusLine.getStatusCode() != 200) {
			//TODO: 貌似饭否没有错误信息说明,如果有的话,这里要补上
//			JSONObject json = null;
//			try {
//				json = new JSONObject(responseString);
//				LibRuntimeException apiException =  FanfouErrorAdaptor.parseError(json);
//				throw apiException;
//			} catch (JSONException e) {
//				throw new LibRuntimeException(ExceptionCode.JSON_PARSE_ERROR, e, ServiceProvider.Fanfou);
//			}
			throw new LibRuntimeException(LibResultCode.E_UNKNOWN_ERROR, ServiceProvider.Fanfou);
		}
		return responseString;
	}
 
Example 4
Source Project: Criteria2Query   Source File: ATLASUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static List<Concept> searchConceptByName(String entity)
		throws UnsupportedEncodingException, IOException, ClientProtocolException {
	JSONObject queryjson = new JSONObject();
	queryjson.accumulate("QUERY", entity);
	System.out.println("queryjson:" + queryjson);
	String vocabularyresult = getConcept(queryjson);
	System.out.println("vocabularyresult  length=" + vocabularyresult.length());
	Gson gson = new Gson();
	JsonArray ja = new JsonParser().parse(vocabularyresult).getAsJsonArray();
	if (ja.size() == 0) {
		System.out.println("size=" + ja.size());
		return null;
	}
	List<Concept> list = gson.fromJson(ja, new TypeToken<List<Concept>>() {
	}.getType());
	return list;
}
 
Example 5
@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, ClientProtocolException, IOException {
  if (queryParam != null) {
    if (uri.indexOf('?') == -1) {
      uri += '?';
    }
    uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
  }
  HttpGet httpGet = new HttpGet(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpGet.setConfig(config);
  }

  try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  }
}
 
Example 6
Source Project: we-cmdb   Source File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * post请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws ClientProtocolException
 * @throws UnknownHostException
 * @throws IOException
 */
public static String post(Map<String, Object> msgs, String url)
        throws ClientProtocolException, UnknownHostException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost request = new HttpPost(url);
        List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
        if (null != msgs) {
            for (Entry<String, Object> entry : msgs.entrySet()) {
                if (entry.getValue() != null) {
                    valuePairs.add(new BasicNameValuePair(entry.getKey(),
                            entry.getValue().toString()));
                }
            }
        }
        request.setEntity(new UrlEncodedFormEntity(valuePairs, CHARSET_UTF_8));
        CloseableHttpResponse resp = httpClient.execute(request);
        return EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
    } finally {
        httpClient.close();
    }
}
 
Example 7
Source Project: knox   Source File: StringResponseHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException
{
  int status = response.getStatusLine().getStatusCode();

  if (status >= 200 && status < 300)
  {
    HttpEntity entity = response.getEntity();
    return entity != null ?EntityUtils.toString(entity) : null;
  }
  else
  {
    throw new ClientProtocolException("Unexcepted response status: " + status);
  }
}
 
Example 8
Source Project: sparkler   Source File: ApacheHttpRestClient.java    License: Apache License 2.0 6 votes vote down vote up
public ApacheHttpRestClient() {

        this.httpClient = HttpClients.createDefault();

        //TODO lambda
        this.responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(
                    final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

       };
    }
 
Example 9
Source Project: mamute   Source File: FeedConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_convert_channel_correctly_info_q() throws ClientProtocolException, IOException {
	FeedConverter feedConverter = new FeedConverter(RSSType.INFO_Q);
	RSSFeed feed = feedConverter.convert(rssInfoQ);
	RSSChannel channel = feed.getChannel();
	
	assertEquals("InfoQ Personalized Feed for Unregistered User - Register to upgrade!", channel.getTitle());
	assertEquals("http://www.infoq.com", channel.getLink());
	assertEquals("This RSS feed is a personalized feed, unique to your account on InfoQ.com.", channel.getDescription());
	RSSItem item = channel.getItems().get(0);
	assertEquals("Article: Applying Lean Thinking to Software Development", item.getTitle());
	assertEquals("http://www.infoq.com/articles/applying-lean-thinking-to-software-development", item.getLink());
	assertEquals("Scrum", item.getCategory().get(0));
	assertEquals("Lean", item.getCategory().get(1));
	
	DateTime rssDay = new DateTime().withDate(2013, 12, 5);
	assertEquals(rssDay.getMonthOfYear(), item.getPubDate().getMonthOfYear());
	assertEquals(rssDay.getYear(), item.getPubDate().getYear());
	assertEquals(rssDay.getDayOfMonth(), item.getPubDate().getDayOfMonth());
}
 
Example 10
Source Project: Criteria2Query   Source File: ConceptMapping.java    License: Apache License 2.0 6 votes vote down vote up
public Integer createConceptByConceptName(String word,String domain) throws UnsupportedEncodingException, ClientProtocolException, IOException{
	Integer conceptId=0;
	//the most related one
	System.out.println("word=" + word);
	System.out.println("domain=" + domain);
	
	List<Concept> econceptlist = ATLASUtil.searchConceptByNameAndDomain(word, domain);
	String expression=generateConceptSetByConcepts(econceptlist);
	long t1=System.currentTimeMillis();  
	JSONObject jo=new JSONObject();
	jo.accumulate("name", word+"_created_by_"+GlobalSetting.c2qversion);
	jo.accumulate("id", 23333);
	String result=HttpUtil.doPost(conceptseturl, jo.toString());
	JSONObject rejo=JSONObject.fromObject(result);
	HttpUtil.doPut(conceptseturl+rejo.getString("id")+"/items",expression);		
	return Integer.valueOf(rejo.getString("id"));
}
 
Example 11
Source Project: galaxy   Source File: HttpClientService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 提交json数据
 *
 * @param url
 * @param json
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {
    // 创建http POST请求
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(this.requestConfig);

    if (json != null) {
        // 构造一个form表单式的实体
        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(stringEntity);
    }

    CloseableHttpResponse response = null;
    try {
        // 执行请求
        response = this.httpClient.execute(httpPost);
        return new HttpResult(response.getStatusLine().getStatusCode(),
                EntityUtils.toString(response.getEntity(), "UTF-8"));
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example 12
Source Project: ribbon   Source File: NFHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T execute(
		final HttpHost target,
		final HttpRequest request,
		final ResponseHandler<? extends T> responseHandler,
		final HttpContext context)
				throws IOException, ClientProtocolException {
    Stopwatch sw = tracer.start();
	try{
		// TODO: replaced method.getQueryString() with request.getRequestLine().getUri()
		LOGGER.debug("Executing HTTP method: {}, uri: {}", request.getRequestLine().getMethod(), request.getRequestLine().getUri());
		return super.execute(target, request, responseHandler, context);
	}finally{
		sw.stop();
	}
}
 
Example 13
Source Project: oxAuth   Source File: ToopherAPI.java    License: MIT License 6 votes vote down vote up
@Override
public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException,
        IOException {
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() >= 300) {
        throw new HttpResponseException(statusLine.getStatusCode(),
                                        statusLine.getReasonPhrase());
    }

    HttpEntity entity = response.getEntity(); // TODO: check entity == null
    String json = EntityUtils.toString(entity);

    try {
        return (JSONObject) new JSONTokener(json).nextValue();
    } catch (JSONException e) {
        throw new ClientProtocolException("Could not interpret response as JSON", e);
    }
}
 
Example 14
Source Project: PoseidonX   Source File: HttpSendClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get 方式请求 ,并返回HTTP_STATUS_CODE码
 * 
 * @param String address 请求地址
 * @param Map<String, Object> params 请求参数
 * @return int
 * @throws ClientProtocolException
 * @throws IOException
 */
public int getReturnHttpCode(String address, Map<String, Object> params) throws ClientProtocolException,
        IOException {

    String paramsStr = buildGetData(params);
    HttpResponse httpResponse = null;
    HttpGet httpGet = new HttpGet(address + paramsStr);
    try {
        httpGet.setHeader("User-Agent", agent);
        httpResponse = httpClient.execute(httpGet);
        return httpResponse.getStatusLine().getStatusCode();
    } finally {
        if (httpResponse != null) {
            try {
                EntityUtils.consume(httpResponse.getEntity()); //会自动释放连接
            } catch (Exception e) {
            }
        }
    }
}
 
Example 15
private static String getResponse(HttpUriRequest method, Map<String, String> headers)
        throws Exception {
    HttpClient client = buildHttpClient(method.getURI().getScheme());
    method.setHeader("charset", "utf-8");

    if (headers != null) {
        Set<String> keys = headers.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            method.setHeader(key, headers.get(key));
            method.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            method.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63");
        }
    }

    HttpResponse response = client.execute(method);
    int status = response.getStatusLine().getStatusCode();
    if (status < 200 || status >= 300) {
        throw new ClientProtocolException("Path:" + method.getURI() + " - Unexpected response status: " + status);
    }
    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity, "UTF-8");
    return body;
}
 
Example 16
Source Project: albert   Source File: GoogleAction.java    License: MIT License 6 votes vote down vote up
@RequestMapping("/search")
public String search(HttpServletRequest request,ModelMap model,String wd,Integer start) throws ClientProtocolException, IOException{
	
	String ip = Tools.getNoHTMLString(getIpAddr(request));
	String temp =wd;
	
	if(null==start){
		wd = wd+"&start="+1+"&num=10";
		start =1;
	}else{
		wd = wd+"&start="+start+"&num=10";
	}
	
	List<GoogleSearchResult>  list = googleService.search(wd);
	
	log.info("ip:"+ip+"搜索了"+temp);
	
	model.addAttribute("list", list);
	model.addAttribute("wd", temp);
	model.addAttribute("start", start);
	
	return "google/search";
}
 
Example 17
Source Project: albert   Source File: TwitterSearchServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public Map<String, Object> check(TwitterSearchHistory tsh) throws RuntimeException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException{
	Map<String, Object> map =new HashMap<String, Object>();
	//检查是否已经搜索过此内容或用户
	TwitterSearchHistoryExample example = new TwitterSearchHistoryExample();
	example.createCriteria().andSearchKeyEqualTo(tsh.getSearchKey())
							.andSearchTypeEqualTo(tsh.getSearchType());
	List<TwitterSearchHistory> list =twitterSearchHistoryMapper.selectByExample(example);
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
	if(null!=list&&list.size()>0){
		tsh =list.get(0);
	}
	if(null!=list&&list.size()>0&&sdf.format(list.get(0).getSearchDate()).compareTo(sdf.format(new Date()))==0){
		map.put("searchId", tsh.getId());
		map.put("status", Boolean.TRUE);
	}else{
		//今天没有搜索过,则调用推特api查询数据
		map = this.addTwitterPostByKey(tsh);
	}
	return map;
}
 
Example 18
Source Project: phabricator-jenkins-plugin   Source File: ConduitAPIClient.java    License: MIT License 6 votes vote down vote up
/**
 * Call the conduit API of Phabricator
 *
 * @param action Name of the API call
 * @param params The data to send to Harbormaster
 * @return The result as a JSONObject
 * @throws IOException If there was a problem reading the response
 * @throws ConduitAPIException If there was an error calling conduit
 */
public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest request = createRequest(action, params);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConduitAPIException(e.getMessage());
    }

    InputStream responseBody = response.getEntity().getContent();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ConduitAPIException(IOUtils.toString(responseBody, Charset.defaultCharset()), response.getStatusLine().getStatusCode());
    }

    JsonSlurper jsonParser = new JsonSlurper();
    return (JSONObject) jsonParser.parse(responseBody);
}
 
Example 19
Source Project: java-client-api   Source File: ConnectedRESTQA.java    License: Apache License 2.0 6 votes vote down vote up
public static void setAuthentication(String level, String restServerName)
		throws ClientProtocolException, IOException {
	DefaultHttpClient client = new DefaultHttpClient();

	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String body = "{\"authentication\": \"" + level + "\"}";

	HttpPut put = new HttpPut("http://" + host_name + ":" + admin_port + "/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);
	}
	client.getConnectionManager().shutdown();
}
 
Example 20
@Test(groups = { "wso2.esb" }, description = "Check for Axis Fault when xml payload is sent with application/json" +
                                             " content type", enabled = true)
public void testAxisFaultWithXmlPayloadAndJSONContentType() throws ClientProtocolException,
                                                           IOException, InterruptedException {
	final HttpPost post = new HttpPost("http://localhost:8480/ESBJAVA3698jsonstockquote/test");
	post.addHeader("Content-Type", "application/json");
	post.addHeader("SOAPAction", "urn:getQuote");
	StringEntity se = new StringEntity(getPayload());
	post.setEntity(se);

       logViewerClient.clearLogs();

	httpClient.execute(post);

       boolean errorLogFound = Utils.checkForLog(logViewerClient,
			"Error occurred while processing document for application/json", 10);
       Assert.assertEquals(errorLogFound, true, "Expected SOAP Response was NOT found in the LOG stream.");
}
 
Example 21
/**
 * Send HTTP GET request to {@link #endpointUrl}, updates {@link #csrfToken}
 * token
 *
 * @return true if {@link #endpointUrl} is accessible
 * @throws IOException
 * @throws ClientProtocolException
 * @throws AuthenticationException
 */
protected void fetchCsrfTokenFromHac() throws ClientProtocolException, IOException, AuthenticationException {
	final HttpGet getRequest = new HttpGet(getEndpointUrl());

	try {
		final HttpResponse response = httpClient.execute(getRequest, getContext());
		final String responseString = new BasicResponseHandler().handleResponse(response);
		csrfToken = getCsrfToken(responseString);

		if (StringUtil.isBlank(csrfToken)) {
			throw new AuthenticationException(ErrorMessage.CSRF_TOKEN_CANNOT_BE_OBTAINED);
		}
	} catch (UnknownHostException error) {
		final String errorMessage = error.getMessage();
		final Matcher matcher = HACPreferenceConstants.HOST_REGEXP_PATTERN.matcher(getEndpointUrl());

		if (matcher.find() && matcher.group(1).equals(errorMessage)) {
			throw new UnknownHostException(
					String.format(ErrorMessage.UNKNOWN_HOST_EXCEPTION_MESSAGE_FORMAT, matcher.group(1)));
		}
		throw error;
	}
}
 
Example 22
Source Project: gocd   Source File: ServerBinaryDownloader.java    License: Apache License 2.0 6 votes vote down vote up
private void handleInvalidResponse(HttpResponse response, String url) throws IOException {
    StringWriter sw = new StringWriter();
    try (PrintWriter out = new PrintWriter(sw)) {
        out.print("Problem accessing GoCD Server at ");
        out.println(url);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            LOG.info("Response code: {}", response.getStatusLine().getStatusCode());
            out.println("Possible causes:");
            out.println("1. Your GoCD Server is down, not accessible or starting up.");
            out.println("2. This agent might be incompatible with your GoCD Server. Please fix the version mismatch between GoCD Server and GoCD Agent.");

            throw new ClientProtocolException(sw.toString());
        } else if (response.getFirstHeader(MD5_HEADER) == null) {
            out.print("Missing required headers '");
            out.print(MD5_HEADER);
            out.println("' in response.");
            throw new ClientProtocolException(sw.toString());
        }
    }
}
 
Example 23
Source Project: WayHoo   Source File: NetUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get方式从服务器获取json数组
 * 
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws JSONException
 */
public static JSONObject getJSONArrayByGet(String uri)
		throws ClientProtocolException, IOException, JSONException {
	Log.i(TAG, "<getJSONArrayByGet> uri:" + uri, Log.APP);
	StringBuilder builder = new StringBuilder();
	HttpClient client = new DefaultHttpClient();
	HttpGet get = new HttpGet(uri);

	HttpResponse response = client.execute(get);

	BufferedReader reader = new BufferedReader(new InputStreamReader(
			response.getEntity().getContent()));
	for (String s = reader.readLine(); s != null; s = reader.readLine()) {
		builder.append(s);
	}

	String jsonString = new String(builder.toString());

	if ("{}".equals(jsonString)) {
		return null;
	}
	Log.i(TAG, "<getJSONArrayByGet> jsonString:" + jsonString, Log.DATA);
	return new JSONObject(jsonString);
}
 
Example 24
Source Project: helix   Source File: CustomRestClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Boolean> handleResponse(HttpResponse httpResponse,
    JsonConverter jsonConverter) throws IOException {
  int status = httpResponse.getStatusLine().getStatusCode();
  if (status == HttpStatus.SC_OK) {
    LOG.info("Expected HttpResponse statusCode: {}", HttpStatus.SC_OK);
    return jsonConverter.convert(getJsonObject(httpResponse));
  } else {
    throw new ClientProtocolException("Unexpected response status: " + status + ", reason: "
        + httpResponse.getStatusLine().getReasonPhrase());
  }
}
 
Example 25
Source Project: rxp-remote-java   Source File: RealexClientTest.java    License: MIT License 5 votes vote down vote up
/**
 * Test receiving a response which has an invalid hash. 
 */
@Test(expected = RealexException.class)
public void sendThreeDSecureInvalidResponseHashTest() throws ClientProtocolException, IOException {
	//get sample response XML
	File file = new File(this.getClass().getResource(THREE_D_SECURE_VERIFY_ENROLLED_RESPONSE_XML_PATH).getPath());
	StreamSource source = new StreamSource(file);
	ThreeDSecureResponse fromXmlResponse = new ThreeDSecureResponse().fromXml(source);

	//add invalid hash
	fromXmlResponse.setHash("invalid hash");

	//mock HttpResponse
	HttpResponse httpResponseMock = mock(HttpResponse.class);
	when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
	when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));

	//create empty request 
	ThreeDSecureRequest request = new ThreeDSecureRequest();

	//create configuration
	HttpConfiguration httpConfiguration = new HttpConfiguration();
	httpConfiguration.setOnlyAllowHttps(false);

	//mock HttpClient instance
	HttpClient httpClientMock = mock(HttpClient.class);
	when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);

	//execute send on client
	RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);
	realexClient.send(request);

	//shouldn't get this far
	Assert.fail("RealexException should have been thrown before this point.");
}
 
Example 26
Source Project: uReplicator   Source File: HttpClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ResponseHandler<String> createResponseBodyExtractor(String path) {
  return new ResponseHandler<String>() {
    @Override
    public String handleResponse(final HttpResponse response) throws IOException {
      int status = response.getStatusLine().getStatusCode();
      if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
      } else {
        throw new ClientProtocolException(
            "Unexpected response status while getting : " + path + " , status : " + status);
      }
    }
  };
}
 
Example 27
Source Project: spring-boot-study   Source File: HttpRestUtils.java    License: MIT License 5 votes vote down vote up
/**
 * delete 方法
 * @param url delete 的 url
 * @param heads Http Head 参数
 * */
public static String delete(String url,Map<String,String> heads) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

        HttpDelete httpDelete = new HttpDelete(url);
        if(heads!=null){
            Set<String> keySet=heads.keySet();
            for(String s:keySet){
                httpDelete.addHeader(s,heads.get(s));
            }
        }
        System.out.println("Executing request " + httpDelete.getRequestLine());

        // Create a custom response handler
        ResponseHandler < String > responseHandler = response -> {
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
        };
        String responseBody = httpclient.execute(httpDelete, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        return responseBody;
    }
}
 
Example 28
@Override
public List<String> handleResponse(HttpResponse response)
		throws ClientProtocolException, IOException {
	List<String> result = new ArrayList<String>();
	String JSONResponse = new BasicResponseHandler()
			.handleResponse(response);
	try {

		// Get top-level JSON Object - a Map
		JSONObject responseObject = (JSONObject) new JSONTokener(
				JSONResponse).nextValue();

		// Extract value of "earthquakes" key -- a List
		JSONArray earthquakes = responseObject
				.getJSONArray(EARTHQUAKE_TAG);

		// Iterate over earthquakes list
		for (int idx = 0; idx < earthquakes.length(); idx++) {

			// Get single earthquake data - a Map
			JSONObject earthquake = (JSONObject) earthquakes.get(idx);

			// Summarize earthquake data as a string and add it to
			// result
			result.add(MAGNITUDE_TAG + ":"
					+ earthquake.get(MAGNITUDE_TAG) + ","
					+ LATITUDE_TAG + ":"
					+ earthquake.getString(LATITUDE_TAG) + ","
					+ LONGITUDE_TAG + ":"
					+ earthquake.get(LONGITUDE_TAG));
		}
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 29
Source Project: slack-api   Source File: StringResponseHandler.java    License: MIT License 5 votes vote down vote up
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
	final StatusLine statusLine = response.getStatusLine();
	int status = statusLine.getStatusCode();
	if (status >= 200 && status < 300) {
		HttpEntity entity = response.getEntity();
		return entity != null ? EntityUtils.toString(entity) : null;
	} else if (status == 429) {
		throw new SlackResponseRateLimitException(Long.valueOf(response.getFirstHeader(RETRY_AFTER_HEADER).getValue()));
	} else {
		throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
	}
}
 
Example 30
Source Project: springtime   Source File: GreetingServerWithApacheTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void helloRest() throws ClientProtocolException, IOException {
	String expectdResponse = "Hello World!";
	String response = Request.Get("http://localhost:8080/web/hello").version(HttpVersion.HTTP_1_1).execute()
			.returnContent().asString();
	assertThat(response).isEqualTo(expectdResponse);
}
 
Example 31
Source Project: ribbon   Source File: NFHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
	// A null target may be acceptable if there is a default target.
	// Otherwise, the null target is detected in the director.
	HttpHost target = null;
	URI requestURI = request.getURI();
	if (requestURI.isAbsolute()) {
		target = URIUtils.extractHost(requestURI);
		if (target == null) {
			throw new ClientProtocolException(
					"URI does not specify a valid host name: " + requestURI);
		}
	}
	return target;
}
 
Example 32
Source Project: charging_pile_cloud   Source File: HttpClientUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 封装HTTP DELETE方法
 *
 * @param
 * @return
 */
public static String delete(String url) throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpDelete httpDelete = new HttpDelete();
    httpDelete.setURI(URI.create(url));
    HttpResponse response = httpClient.execute(httpDelete);
    String httpEntityContent = getHttpEntityContent(response);
    httpDelete.abort();
    return httpEntityContent;
}
 
Example 33
Source Project: aws-xray-sdk-java   Source File: TracedHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;

    final URI requestUri = request.getURI();
    if (requestUri.isAbsolute()) {
        target = URIUtils.extractHost(requestUri);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: "
                    + requestUri);
        }
    }
    return target;
}
 
Example 34
Source Project: clouddisk   Source File: BaseResponseHandle.java    License: MIT License 5 votes vote down vote up
public M handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
	executeBefore(response);
	final HttpEntity entity = response.getEntity();
	final String result = EntityUtils.toString(entity, Consts.UTF_8);
	final M m = desializer(result);
	saveCookie();
	executeAfter(response);
	return m;
}
 
Example 35
Source Project: ghwatch   Source File: AuthenticationManager.java    License: Apache License 2.0 5 votes vote down vote up
private String remoteLogin(Context context, GHCredentials cred, String otp) throws JSONException, NoRouteToHostException, AuthenticationException,
    ClientProtocolException, URISyntaxException, IOException {
  Map<String, String> headers = null;
  otp = Utils.trimToNull(otp);
  if (otp != null) {
    headers = new HashMap<String, String>();
    headers.put("X-GitHub-OTP", otp);
  }
  String content = GH_AUTH_REQ_CONTENT.replace("*fp*", System.currentTimeMillis() + "");
  Response<String> resp = RemoteSystemClient.putToURL(context, cred, GH_AUTH_REQ_URL, headers, content);
  JSONObject jo = new JSONObject(resp.data);
  return jo.getString("token");
}
 
Example 36
Source Project: tutorials   Source File: RestClientLiveManualTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException {
    final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}
 
Example 37
Source Project: zheshiyigeniubidexiangmu   Source File: HttpUtilManager.java    License: MIT License 5 votes vote down vote up
public HttpResponse getResponse(String url) throws ClientProtocolException, IOException {
	IdleConnectionMonitor();
	HttpRequestBase method = this.httpGetMethod(url);

	method.setConfig(requestConfig);
	HttpResponse response = client.execute(method);
	return response;
}
 
Example 38
Source Project: forge-api-java-client   Source File: OAuth2ThreeLegged.java    License: Apache License 2.0 5 votes vote down vote up
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException, ApiException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(request);

    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity);

    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        throw new ApiException(status, body);
    }

    return body;
}
 
Example 39
Source Project: Examples   Source File: DeleteExample.java    License: MIT License 5 votes vote down vote up
/**
 * Perform delete request.
 * @param httpDelete
 */
public static void httpDeleteRequest(HttpDelete httpDelete) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            /* Get status code */
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                /* Convert response to String */
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpDelete, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 40
Source Project: CSipSimple   Source File: Downloader.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    FileOutputStream fos = new FileOutputStream(mFile.getPath());
    
    HttpEntity entity = response.getEntity();
    boolean done = false;
    
    try {
     if (entity != null) {
         Long length = entity.getContentLength();
         InputStream input = entity.getContent();
         byte[] buffer = new byte[4096];
         int size  = 0;
         int total = 0;
         while (true) {
             size = input.read(buffer);
             if (size == -1) break;
             fos.write(buffer, 0, size);
             total += size;
             mProgress.run(total, length);
         }
         done = true;
     }
    }catch(IOException e) {
    	Log.e(THIS_FILE, "Problem on downloading");
    }finally {
    	fos.close();
    }
    
    return done;
}