org.apache.http.client.ClientProtocolException Java Examples

The following examples show how to use org.apache.http.client.ClientProtocolException. 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 check out the related API usage on the sidebar.
Example #1
Source File: HttpSendClient.java    From PoseidonX with 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 #2
Source File: HttpUtils.java    From we-cmdb with 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 #3
Source File: SimpleGetRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: ATLASUtil.java    From Criteria2Query with 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
Source File: AbstractHACCommunicationManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: ServerBinaryDownloader.java    From gocd with 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 #7
Source File: Item.java    From customer-review-crawler with 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 #8
Source File: NetUtils.java    From WayHoo with 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 #9
Source File: TestIssue105.java    From cloud-odata-java with 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 #10
Source File: FanfouResponseHandler.java    From YiBo with 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 #11
Source File: StringResponseHandler.java    From knox with 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 #12
Source File: ApacheHttpRestClient.java    From sparkler with 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 #13
Source File: ConceptMapping.java    From Criteria2Query with 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 #14
Source File: FeedConverterTest.java    From mamute with 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 #15
Source File: GoogleAction.java    From albert with 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 #16
Source File: TwitterSearchServiceImpl.java    From albert with 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 #17
Source File: ToopherAPI.java    From oxAuth with 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 #18
Source File: HttpPostGet.java    From ApiManager with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #19
Source File: ConduitAPIClient.java    From phabricator-jenkins-plugin with 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 #20
Source File: NFHttpClient.java    From ribbon with 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 #21
Source File: HttpClientService.java    From galaxy with 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 #22
Source File: ConnectedRESTQA.java    From java-client-api with 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 #23
Source File: ESBJAVA_3698_MessageBuildingWithDifferentPayloadAndContentTypeTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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 #24
Source File: DeleteExample.java    From Examples with 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 #25
Source File: RestClientLiveManualTest.java    From tutorials with 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 #26
Source File: AuthenticationManager.java    From ghwatch with 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 #27
Source File: Downloader.java    From CSipSimple with 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;
}
 
Example #28
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void listChildren(CloseableHttpClient httpclient, long parentId) throws ClientProtocolException, IOException {

		//System.out.println("sid: " + httpclient);

		List<NameValuePair> params = new LinkedList<NameValuePair>();
		params.add(new BasicNameValuePair("folderId", String.valueOf(parentId)));

		StringBuilder requestUrl = new StringBuilder(BASE_PATH + "/services/rest/folder/listChildren");
		String querystring = URLEncodedUtils.format(params, "utf-8");
		requestUrl.append("?");
		requestUrl.append(querystring);

		System.out.println(requestUrl);

		//CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet method = new HttpGet(requestUrl.toString());
		method.setHeader("Accept", "application/json");

		CloseableHttpResponse response1 = httpclient.execute(method);

		try {
			System.out.println(response1.getStatusLine());
			HttpEntity entity2 = response1.getEntity();

			String respoBody = EntityUtils.toString(entity2, "UTF-8");
			System.out.println(respoBody);

			// do something useful with the response body
			// and ensure it is fully consumed
			EntityUtils.consume(entity2);
		} finally {
			response1.close();
		}
	}
 
Example #29
Source File: ClusterDependentTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
protected static String sendGetHttpRequestToMock(String path, Map<String, String> parameters) throws Exception {
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost("localhost").setPort(mock().getHttpPort()).setPath(path);
    for (Map.Entry<String, String> entry: parameters.entrySet()) {
        builder.setParameter(entry.getKey(), entry.getValue());
    }
    HttpGet request = new HttpGet(builder.build());
    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(request);
    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
    return EntityUtils.toString(response.getEntity());
}
 
Example #30
Source File: BaseResponseHandle.java    From clouddisk with 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;
}