public DatarouterHttpResponse(HttpResponse response, HttpClientContext context, Consumer<HttpEntity> httpEntityConsumer){ this.response = response; this.cookies = context.getCookieStore().getCookies(); if(response != null){ this.statusCode = response.getStatusLine().getStatusCode(); this.entity = ""; HttpEntity httpEntity = response.getEntity(); if(httpEntity == null){ return; } if(httpEntityConsumer != null){ httpEntityConsumer.accept(httpEntity); return; } try{ this.entity = EntityUtils.toString(httpEntity); }catch(IOException e){ logger.error("Exception occurred while reading HTTP response entity", e); }finally{ EntityUtils.consumeQuietly(httpEntity); } } }
public static String checkRandCodeAnsyn(String randCode) { Objects.requireNonNull(randCode); ResultManager.touch(randCode, "confirmRandCode"); CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.checkRandCodeAnsyn); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity(checkRandCodeAnsynParam(), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))); String result = StringUtils.EMPTY; try (CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); logger.debug(result); } catch (IOException e) { logger.error("checkRandCodeAnsyn error", e); } return result; }
private void register(RegisterModel model) throws Exception { String url = "http://" + properties.getScouter().getHost() + ":" + properties.getScouter().getPort() + "/register"; String param = new Gson().toJson(model); HttpPost post = new HttpPost(url); post.addHeader("Content-Type","application/json"); post.setEntity(new StringEntity(param)); CloseableHttpClient client = HttpClientBuilder.create().build(); // send the post request HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { logger.info("Register message sent to [{}] for [{}].", url, model.getObject().getDisplay()); } else { logger.warn("Register message sent failed. Verify below information."); logger.warn("[URL] : " + url); logger.warn("[Message] : " + param); logger.warn("[Reason] : " + EntityUtils.toString(response.getEntity(), "UTF-8")); } }
private static String execute0(HttpUriRequest httpUriRequest) throws Exception { CloseableHttpResponse closeableHttpResponse = null; String var4; try { closeableHttpResponse = closeableHttpClient.execute(httpUriRequest); String response = EntityUtils.toString(closeableHttpResponse.getEntity(), CHARSET); var4 = response; } catch (Exception var7) { throw var7; } finally { CloseUtils.close(closeableHttpResponse); } return var4; }
private synchronized void PostParam(String url, List<BasicNameValuePair> parameters) throws Exception { HttpPost post = new HttpPost(url); String result = ""; try { post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); result = EntityUtils.toString(httpEntity, "utf-8"); } catch (java.io.IOException e) { e.printStackTrace(); } finally { JSONObject jsonObject = new JSONObject(result); String status = jsonObject.getString("status"); if (!status.equals("success")) { throw new Exception(jsonObject.getString("msg")); } System.out.println(status); } }
public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context, ObjectMapper _mapper) { this.response = response; this.httpClient = httpClient; this.request = request; this.context = context; mapper = _mapper; try { HttpEntity entity = response.getEntity(); if (entity != null) { this.entity = new BufferedHttpEntity(entity); } else { this.entity = new BasicHttpEntity(); } EntityUtils.consumeQuietly(entity); this.response.close(); } catch (IOException e) { logger.warn(e.getMessage()); } }
/** * Constructor * * @param response the http response */ public Response( final HttpResponse response ) { this.status = response.getStatusLine( ); this.headers = response.getAllHeaders( ); try { this.entityContent = EntityUtils.toByteArray( response.getEntity( ) ); // EntityUtils.consume( response.getEntity( ) ); } catch ( IllegalArgumentException | IOException e ) { // ok } }
static SonarHttpRequester getSonarHttpRequester(GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance) { try { HttpGet request = new HttpGet(getSonarApiServerVersion(globalConfigDataForSonarInstance)); HttpClientContext context = HttpClientContext.create(); CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = client.execute(request, context); String sonarVersion = EntityUtils.toString(response.getEntity()); if (majorSonarVersion(sonarVersion) <= 5) { return new SonarHttpRequester5x(); } else if (majorSonarVersion(sonarVersion) >= 6 && minorSonarVersion(sonarVersion) == 0) { return new SonarHttpRequester60(); } else if (majorSonarVersion(sonarVersion) >= 6 && minorSonarVersion(sonarVersion) >= 1) { return new SonarHttpRequester61(); } else { throw new UnsuportedVersionException("Plugin doesn't suport this version of sonar api! Please contact the developer."); } } catch (IOException e) { throw new ApiConnectionException(e.getLocalizedMessage()); } }
protected String[] copyStaging(ItemId itemId, String token) throws IOException { HttpResponse stagingResponse = execute( new HttpPost(appendQueryString(context.getBaseUrl() + "api/item/copy", queryString("uuid", itemId.getUuid(), "version", Integer.toString(itemId.getVersion())))), true, token); try { assertResponse(stagingResponse, 201, "201 not returned from staging creation"); } finally { EntityUtils.consume(stagingResponse.getEntity()); } ObjectNode stagingJson = (ObjectNode) getEntity(stagingResponse.getLastHeader("Location").getValue(), token); String stagingUuid = stagingJson.get("uuid").asText(); String stagingDirUrl = stagingJson.get("links").get("self").asText(); return new String[]{stagingUuid, stagingDirUrl}; }
protected void doHandle(String uriId,HttpUriRequest request,Object result){ if(this.isError(result)){ String content = null; if(request instanceof HttpEntityEnclosingRequestBase){ HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request; HttpEntity entity = request_base.getEntity(); //MULTIPART_FORM_DATA 请求类型判断 if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){ try { content = EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); } } if(logger.isErrorEnabled()){ logger.error("URI[{}] {} Content:{} Result:{}", uriId, request.getURI(), content == null ? "multipart_form_data" : content, result == null? null : JsonUtil.toJSONString(result)); } } this.handle(uriId,request.getURI().toString(),content,result); } }
/** * Realiza a emissão do boleto bancário para adicionar saldo à subconta digital * @param tokenCartao: Token da subconta/cartão ao qual o saldo será adicionado * @param valor: valor do saldo à ser adicionado * @return Boleto */ public Boleto addBalance(String tokenCartao, double valor) throws IOException, PJBankException { PJBankClient client = new PJBankClient(this.endPoint.concat("/").concat(tokenCartao)); HttpPost httpPost = client.getHttpPostClient(); httpPost.addHeader("x-chave-conta", this.chave); JSONObject params = new JSONObject(); params.put("valor", valor); httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8)); String response = EntityUtils.toString(client.doRequest(httpPost).getEntity()); JSONObject responseObject = new JSONObject(response).getJSONObject("data"); return new Boleto(responseObject.getString("nosso_numero"), responseObject.getString("link_boleto"), responseObject.getString("linha_digitavel")); }
@Nullable private static StepicWrappers.TokenInfo getTokens(@NotNull final List<NameValuePair> parameters) { final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); final HttpPost request = new HttpPost(EduStepicNames.TOKEN_URL); request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); try { final CloseableHttpClient client = EduStepicClient.getHttpClient(); final CloseableHttpResponse response = client.execute(request); final StatusLine statusLine = response.getStatusLine(); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; EntityUtils.consume(responseEntity); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { return gson.fromJson(responseString, StepicWrappers.TokenInfo.class); } else { LOG.warn("Failed to get tokens: " + statusLine.getStatusCode() + statusLine.getReasonPhrase()); } } catch (IOException e) { LOG.warn(e.getMessage()); } return null; }
private static int getAttemptId(@NotNull Task task) throws IOException { final StepicWrappers.AdaptiveAttemptWrapper attemptWrapper = new StepicWrappers.AdaptiveAttemptWrapper(task.getStepId()); final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.ATTEMPTS); post.setEntity(new StringEntity(new Gson().toJson(attemptWrapper))); final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return -1; setTimeout(post); final CloseableHttpResponse httpResponse = client.execute(post); final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity entity = httpResponse.getEntity(); final String entityString = EntityUtils.toString(entity); EntityUtils.consume(entity); if (statusCode == HttpStatus.SC_CREATED) { final StepicWrappers.AttemptContainer container = new Gson().fromJson(entityString, StepicWrappers.AttemptContainer.class); return (container.attempts != null && !container.attempts.isEmpty()) ? container.attempts.get(0).id : -1; } return -1; }
/** * Get trend data; interval is in months. Up to five keywords may be entered. Calling this frequently will result in denied query * @param keywords Keywords to query. Up to five may be queried at a time * @param startDate Start date. Format is in "mm/yyyy" * @param deltaMonths Time, in months, from start date for which to retrieve data * @return Trend data */ public static Trend getTrend(String[] keywords, String startDate, int deltaMonths) { StringBuilder sb = new StringBuilder(); sb.append(PUBLIC_URL); StringBuilder param_q = new StringBuilder(); for(String each : keywords) { param_q.append(each); param_q.append(','); } param_q.setLength(param_q.length()-1); append(sb, "q", param_q.toString()); append(sb, "cid", "TIMESERIES_GRAPH_0"); append(sb, "export", "3"); append(sb, "date", startDate + "+" + deltaMonths + "m"); append(sb, "hl", "en-US"); HttpPost post = new HttpPost(sb.toString()); post.addHeader("Cookie", cookieString); String response = null; try(CloseableHttpResponse httpResponse = httpClient.execute(post)) { HttpEntity httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e.printStackTrace(); } return parseResponse(response, keywords); }
protected ObjectNode putItemError(String itemUri, String json, String token, int responseCode, Object... paramNameValues) throws Exception { final HttpPut request = new HttpPut(appendQueryString(itemUri, queryString(paramNameValues))); final StringEntity ent = new StringEntity(json, "UTF-8"); ent.setContentType("application/json"); request.setEntity(ent); HttpResponse response = execute(request, false, token); try { assertResponse(response, responseCode, "Incorrect response code"); ObjectNode error = (ObjectNode) mapper.readTree(response.getEntity().getContent()); return error; } finally { EntityUtils.consume(response.getEntity()); } }
@Override protected final <T extends Serializable, Method extends BotApiMethod<T>> T sendApiMethod(Method method) throws TelegramApiException { method.validate(); String responseContent; try { String url = getBaseUrl() + method.getMethod(); HttpPost httppost = new HttpPost(url); httppost.setConfig(requestConfig); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httppost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); } } catch (IOException e) { throw new TelegramApiException("Unable to execute " + method.getMethod() + " method", e); } return method.deserializeResponse(responseContent); }
private byte[] bytes(HttpEntity entity){ try { return EntityUtils.toByteArray(entity); } catch (IOException e) { error(e); } return null; }
@SuppressWarnings("unchecked") private Map<String, RouteConfig> getRouterMap() { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Constants.DEFAULT_TIMEOUT) .setConnectionRequestTimeout(Constants.DEFAULT_TIMEOUT).setSocketTimeout(Constants.DEFAULT_TIMEOUT) .build(); HttpClient httpClient = this.httpPool.getResource(); try { StringBuilder sb = new StringBuilder(50); sb.append(this.getServerDesc().getRegistry()) .append(this.getServerDesc().getRegistry().endsWith("/") ? "" : "/") .append(this.getServerDesc().getServerApp()).append("/routers"); HttpGet get = new HttpGet(sb.toString()); get.setConfig(requestConfig); // 创建参数队列 HttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity, "UTF-8"); ObjectMapper mapper = JsonMapperUtil.getJsonMapper(); return mapper.readValue(body, Map.class); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } finally { this.httpPool.release(httpClient); } }
public static String getPassengers() { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.passenger); httpPost.addHeader(CookieManager.cookieHeader()); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpPost)) { result = EntityUtils.toString(response.getEntity()); List<Passenger> passengers = PassengerUtil.parsePassenger(result); ResultManager.touch(passengers, "passengers"); } catch (IOException e) { logger.error("getPassengers error", e); } return result; }
public static String checkUser() { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.checkUser); httpPost.addHeader(CookieManager.cookieHeader()); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { logger.error("checkUser error", e); } return result; }
/** * Retorna os dados cadastrais referentes à credencial informada para conta digital * @param credencial: Conjunto de credencial e chave para a conta que deseja consultar * @return Cliente: Dados cadastrais da credencial informada */ public Cliente get(Credencial credencial) throws IOException, PJBankException { PJBankClient client = new PJBankClient(this.endPoint.concat("/").concat(credencial.getCredencial())); HttpGet httpGet = client.getHttpGetClient(); httpGet.addHeader("x-chave-conta", credencial.getChave()); String response = EntityUtils.toString(client.doRequest(httpGet).getEntity()); JSONObject responseObject = new JSONObject(response); Cliente cliente = new Cliente(); cliente.setNome(responseObject.getString("nome_empresa")); cliente.setCpfCnpj(responseObject.getString("cnpj")); Endereco endereco = new Endereco(); endereco.setLogradouro(responseObject.getString("endereco")); endereco.setNumero(responseObject.getInt("numero")); endereco.setComplemento(responseObject.getString("complemento")); endereco.setBairro(responseObject.getString("bairro")); endereco.setCidade(responseObject.getString("cidade")); endereco.setEstado(responseObject.getString("estado")); endereco.setCep(responseObject.getString("cep")); cliente.setEndereco(endereco); String telefone = responseObject.getString("telefone"); cliente.setDdd(Integer.parseInt(telefone.substring(0, 2))); cliente.setTelefone(Long.parseLong(telefone.substring(2, telefone.length()))); cliente.setEmail(responseObject.getString("email")); cliente.setStatus("ativa".equalsIgnoreCase(responseObject.getString("status"))); return cliente; }
public static String checkOrderInfo(TrainQuery query) { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { logger.error("checkUser error", e); } return result; }
@Override public String getJsonMachineFromCAdvisor() { String result = ""; try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.3/machine"); CloseableHttpResponse response = httpclient.execute(httpget); try { result = EntityUtils.toString(response.getEntity()); if (logger.isDebugEnabled()) { logger.debug(result); } } finally { response.close(); } } catch (Exception e) { logger.error("" + e); } return result; }
public static String getToken() { String host = "https://oapi.dingtalk.com"; String path = "/gettoken"; String method = "GET"; Map<String, String> headers = new HashMap<>(); Map<String, String> querys = new HashMap<>(); querys.put("corpid", corpid); querys.put("corpsecret", corpsecret); try { HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys); String json = (EntityUtils.toString(response.getEntity())); Map<String, String> tokenMap = JSON.parseObject((json), new TypeReference<Map<String, String>>() { }); return tokenMap.get("access_token"); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Performs the second step in oauth process. * @param code code received from redirect URL in {@link #oauthStepOneRedirectURL(String)} * @param redirectURI one of the redirect URI's registered in google console * @return the credentials returned from the authorization process * @throws IOException thrown because of issue with sending request or parsing response */ public Credentials oauthStepTwo(String code, String redirectURI) throws IOException{ //assemble parameters Map<String, String> params = new HashMap<>(); params.put("code", code); params.put("client_id", clientID); params.put("client_secret", clientSecret); params.put("redirect_uri", redirectURI); params.put("grant_type", "authorization_code"); //Send the request to google HttpResponse response = callProvider.post(GOOGLE_TOKEN_URL, params); //Get the response String body = EntityUtils.toString(response.getEntity()); //Check the status if(response.getStatusLine().getStatusCode() != 200) { log.error("Failed to authenticate. Received status code " + response.getStatusLine().getStatusCode()); log.debug("Body: " + body); return null; } //Return the credentials return new Credentials(body); }
private static void askForUpdate() { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(SpringConfiguration.UPDATE_SERVER_ADDRESS); try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) { //System.out.println(Arrays.asList(response1.getAllHeaders())); HttpEntity entity = response1.getEntity(); try (BufferedReader bis = new BufferedReader(new InputStreamReader(entity.getContent()))) { String line = null; String content = ""; while ((line = bis.readLine()) != null) { content += line; } logger.warn("Update message: " + content); } EntityUtils.consume(entity); } catch (IOException e) { logger.error("Unable to reach update server", e); } }
/** * 下载文件 * * @param url URL * @return 文件的二进制流,客户端使用outputStream输出为文件 */ public static byte[] getFile(String url) { try { Request request = Request.Get(url); HttpEntity resEntity = request.execute().returnResponse().getEntity(); return EntityUtils.toByteArray(resEntity); } catch (Exception e) { logger.error("postFile请求异常," + e.getMessage() + "\n post url:" + url); e.printStackTrace(); } return null; }
public static String triggerHttpGet(String requestUrl) { String result = null; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://" + requestUrl); try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); log.debug("Received response: " + result); } else { log.error("Request not successful. StatusCode was " + response.getStatusLine().getStatusCode()); } } catch (IOException e) { log.error("Error executing the request.", e); } return result; }
/** * Returns the latest Ether price in Wei * @return Latest Ether price in Wei */ public EtherPrice lastEtherPrice() { HttpGet get = new HttpGet(PUBLIC_URL + "?module=stats&action=ethprice&apikey=" + API_KEY); String response = null; try(CloseableHttpResponse httpResponse = httpClient.execute(get)) { HttpEntity httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e.printStackTrace(); } @SuppressWarnings("rawtypes") ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response); EtherPrice current = new EtherPrice(); for(int j = 0; j < a.size(); j++) current.addData(a.get(j)); return current; }
public static void setAuthentication(String level,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"authentication\": \""+level+"\"}"; 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); } }
public static void main(String[] args) throws ParseException, IOException { HttpRequestUtil util = new HttpRequestUtil(); CloseableHttpClient client = util.setDoubleInit(); Map<String,String> map = new HashMap<>(); CloseableHttpResponse httpPost = util.httpPost(client, "https://127.0.0.1:8443/pwp-web/login.do", map); HttpEntity entity = httpPost.getEntity(); String string = EntityUtils.toString(entity, Charset.defaultCharset()); System.out.println(string); }
/** * Experimental. Returns the value from a storage position at a given address * @param address Address * @param position Storage position * @return Value from storage position */ public String getStorageAt(String address, BigInteger position) { HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_getStorageAt&address=" + address + "&position=" + "0x" + position.toString(16) + "&tag=latest" + "&apikey=" + API_KEY); String response = null; try(CloseableHttpResponse httpResponse = httpClient.execute(get)) { HttpEntity httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e.printStackTrace(); } @SuppressWarnings("rawtypes") ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response); for(int j = 0; j < a.size(); j++) if(a.get(j).getName().toString().equals("result")) return a.get(j).getValue().toString(); return null; // Null should not be expected when API is functional }
/** * Perform an Oauth2 callback to the Discord servers with the token given by the user's approval * @param token Token from user * @param res Passed on response * @throws ClientProtocolException Error in HTTP protocol * @throws IOException Encoding exception or error in protocol * @throws NoAPIKeyException No API keys set */ static void oauth(String token, Response res) throws ClientProtocolException, IOException, NoAPIKeyException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost("https://discordapp.com/api/oauth2/token"); List<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("client_id", Bot.getInstance().getApiKeys().get("dashboardid"))); nvp.add(new BasicNameValuePair("client_secret", Bot.getInstance().getApiKeys().get("dashboardsecret"))); nvp.add(new BasicNameValuePair("grant_type", "authorization_code")); nvp.add(new BasicNameValuePair("code", token)); post.setEntity(new UrlEncodedFormEntity(nvp)); String accessToken; CloseableHttpResponse response = httpclient.execute(post); try { System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); JsonObject authJson; try(BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) { authJson = Json.parse(buffer.lines().collect(Collectors.joining("\n"))).asObject(); } accessToken = authJson.getString("access_token", ""); EntityUtils.consume(entity); getGuilds(res, accessToken); } finally { response.close(); } }
private String[] downloadConfig(String url) throws Exception { try { HttpClient client = new DefaultHttpClient(); HttpGet requestGet = new HttpGet(url); requestGet.addHeader("X-Android-MODEL", Build.MODEL); requestGet.addHeader("X-Android-SDK_INT", Integer.toString(Build.VERSION.SDK_INT)); requestGet.addHeader("X-Android-RELEASE", Build.VERSION.RELEASE); requestGet.addHeader("X-App-Version", AppVersion); requestGet.addHeader("X-App-Install-ID", AppInstallID); requestGet.setHeader("User-Agent", System.getProperty("http.agent")); HttpResponse response = client.execute(requestGet); String configString = EntityUtils.toString(response.getEntity(), "UTF-8"); String[] lines = configString.split("\\n"); return lines; } catch (Exception e) { throw new Exception(String.format("Download config file from %s failed.", url)); } }
private void sendRequestWithHttpClient_history(){ new Thread(new Runnable() { @Override public void run() { HttpClient httpCient = new DefaultHttpClient(); //创建HttpClient对象 HttpGet httpGet = new HttpGet(url+"/history.php?action=getSearchHistory&id="+resp_user.getUser_id() +"&username="+resp_user.getUsername()); try { HttpResponse httpResponse = httpCient.execute(httpGet);//第三步:执行请求,获取服务器发还的相应对象 if((httpResponse.getEntity())!=null){ HttpEntity entity =httpResponse.getEntity(); String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串 resp_user.setSearchHistory(response); resp_user.updateAll("User_id > ?","0"); } }catch (Exception e){ e.printStackTrace(); } } }).start(); }
/** * Sends the {@code report} to the {@code controller}. * @param controller the controller to contact. * @param client the HTTP client to contact with. * @param report the report to send. * @throws IOException when report cannot be sent. */ public static void postReport(Controller controller, Report report, CloseableHttpClient client) throws IOException { String reportResource = controller.getLogResource(); String json = report.toJson(); HttpHost proxy = controller.getProxy(AppConfigurationService.getConfigurations().getProxy()).toHttpHost(); HttpPost httpPost = new HttpPost(reportResource); StringEntity data = new StringEntity(json); data.setContentType("application/json"); httpPost.setEntity(data); controller.getAuthentication(AppConfigurationService.getConfigurations().getAuthentication()) .forEach(httpPost::setHeader); if (proxy != null) httpPost.setConfig(RequestConfig.custom().setProxy(proxy).build()); try (CloseableHttpResponse response = client.execute(httpPost)) { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } }
/** * obtain the get request param * * @return the param string */ private String getRequestParamString() { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (!StringUtils.isBlank(name)) { nameValuePairs.add(new BasicNameValuePair(SmnConstants.NAME, name)); } String param = ""; if (!nameValuePairs.isEmpty()) { try { param = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, Charset.forName("UTF-8"))); } catch (IOException e) { throw new RuntimeException("get request param error"); } } return param; }
private ActionFuture<String> start(String method, String path, HttpEntity body) { PlainActionFuture<String> future = new PlainActionFuture<>(); Map<String, String> params = new HashMap<>(); params.put("refresh", "wait_for"); params.put("error_trace", ""); client().performRequestAsync(method, docPath() + path, params, body, new ResponseListener() { @Override public void onSuccess(Response response) { try { future.onResponse(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8)); } catch (IOException e) { future.onFailure(e); } } @Override public void onFailure(Exception exception) { future.onFailure(exception); } }); return future; }
/** * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client */ @SuppressWarnings("unchecked") public void testInternalHttpRequest() throws Exception { ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor.forClass(HttpAsyncRequestProducer.class); int times = 0; for (String httpMethod : getHttpMethods()) { HttpUriRequest expectedRequest = performRandomRequest(httpMethod); verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)); HttpUriRequest actualRequest = (HttpUriRequest)requestArgumentCaptor.getValue().generateRequest(); assertEquals(expectedRequest.getURI(), actualRequest.getURI()); assertEquals(expectedRequest.getClass(), actualRequest.getClass()); assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders()); if (expectedRequest instanceof HttpEntityEnclosingRequest) { HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity(); if (expectedEntity != null) { HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity(); assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity)); } } } }
/** * Implemented receiveGET from Interface interfaceAPI (see for more details) * * @throws IOException IO Error * @throws ParseException Parse Error */ public void receiveGET () throws IOException, ParseException { JSONArray JSONArray = readResponseJSON(API_IDENTIFIER, EntityUtils.toString(httpEntity, "UTF-8"), "annotations"); if (JSONArray != null) { for (Object aJSONArray : JSONArray) { JSONObject object = (JSONObject) aJSONArray; ResponseEntry entity = new ResponseEntry(); String s = (String) object.get("spot"); s = addEntity(s); // Add Entity only if it is new and has not been added before if (s != null) { entity.setEntry(s); entity.setConfidence((Double) object.get("confidence")); foundEntryList.add(entity); } } // Sort the Array List Entities from A to Z Collections.sort(foundEntryList, new SortResponseEntity()); } }