@Override public <REQ> CloseableHttpResponse sendHttpPost(String url, REQ request) { CloseableHttpResponse execute = null; String requestJson = GsonUtils.toJson(request); try { LOGGER.log(Level.FINER, "Send POST request:" + requestJson + " to url-" + url); HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(requestJson, "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); execute = this.httpClientFactory.getHttpClient().execute(httpPost); } catch (IOException e) { LOGGER.log(Level.SEVERE, "was unable to send POST request:" + requestJson + " (displaying first 1000 chars) from url-" + url, e); } return execute; }
/** * Simple Http Post. * * @param path the path * @param payload the payload * @return the closeable http response * @throws URISyntaxException the URI syntax exception * @throws IOException Signals that an I/O exception has occurred. * @throws MininetException the MininetException */ public CloseableHttpResponse simplePost(String path, String payload) throws URISyntaxException, IOException, MininetException { URI uri = new URIBuilder() .setScheme("http") .setHost(mininetServerIP.toString()) .setPort(mininetServerPort.getPort()) .setPath(path) .build(); CloseableHttpClient client = HttpClientBuilder.create().build(); RequestConfig config = RequestConfig .custom() .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS) .setSocketTimeout(CONNECTION_TIMEOUT_MS) .build(); HttpPost request = new HttpPost(uri); request.setConfig(config); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(payload)); CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() >= 300) { throw new MininetException(String.format("failure - received a %d for %s.", response.getStatusLine().getStatusCode(), request.getURI().toString())); } return response; }
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 jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://" + ip + ":8080/proyecto-gson/servidordetener?id=" + user.getId()); CloseableHttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); response.close(); } catch (IOException ex) { Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex); } user = null; jLabel1.setForeground(Color.red); url.setText(""); jlabelSQL.setText(""); this.setTitle("App [ID:?]"); }
@Test public void testEdit() throws URISyntaxException, ClientProtocolException, IOException { String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json"; URIBuilder urlb = new URIBuilder(url); // 参数 urlb.setParameter("id", "1"); urlb.setParameter("marketName", "eoemarket"); urlb.setParameter("catalog", "1"); urlb.setParameter("subCatalog", "15"); urlb.setParameter("subCatalogName", "系统工具1"); urlb.setParameter("targetCatalog", "1"); urlb.setParameter("targetSubCatalog", "14"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(urlb.build()); HttpResponse response = httpClient.execute(httpPost); logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity()); }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() != null || authState.hasAuthOptions()) { return; } // If no authState has been established and this is a PUT or POST request, add preemptive authorisation String requestMethod = request.getRequestLine().getMethod(); if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (credentials == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, credentials); } }
public static void getRequest(String type) { HttpResponse httpResponse = null; try { if (type.equals("GET")) { HttpGet httpGet = new HttpGet(""); ; httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"); httpResponse = client.execute(httpGet); } else if (type.equals("POST")) { HttpPost httpPost = new HttpPost(); } } catch (IOException e) { e.printStackTrace(); } }
/** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); }
private HttpRequestBase getRequest(String url){ switch(method){ case DELETE: return new HttpDelete(url); case GET: return new HttpGet(url); case HEAD: return new HttpHead(url); case PATCH: return new HttpPatch(url); case POST: return new HttpPost(url); case PUT: return new HttpPut(url); default: throw new IllegalArgumentException("Invalid or null HttpMethod: " + method); } }
private HttpUriRequest c() { if (this.f != null) { return this.f; } if (this.j == null) { byte[] b = this.c.b(); CharSequence b2 = this.c.b(AsyncHttpClient.ENCODING_GZIP); if (b != null) { if (TextUtils.equals(b2, "true")) { this.j = b.a(b); } else { this.j = new ByteArrayEntity(b); } this.j.setContentType(this.c.c()); } } HttpEntity httpEntity = this.j; if (httpEntity != null) { HttpUriRequest httpPost = new HttpPost(b()); httpPost.setEntity(httpEntity); this.f = httpPost; } else { this.f = new HttpGet(b()); } return this.f; }
/** * Creates an object of the given dataModelName and moduleName * the appname which is set in this object will be used * * @param moduleName * the modulenname * @param dataModelName * the name of the datamodels * @param otherFieldsObject * the other fields to set as JSONObject (the @type field will be added automatically) * @return request object to check status codes and return values */ public Response createObject( String moduleName, String dataModelName, JSONObject otherFieldsObject ) { final HttpPost request = new HttpPost( this.yambasBase + "apps/" + this.appName + "/models/" + moduleName + "/" + dataModelName ); setAuthorizationHeader( request ); request.addHeader( "ContentType", "application/json" ); request.addHeader( "x-apiomat-apikey", this.apiKey ); request.addHeader( "x-apiomat-system", this.system.toString( ) ); request.addHeader( "x-apiomat-sdkVersion", this.sdkVersion ); try { otherFieldsObject.put( "@type", moduleName + '$' + dataModelName ); final HttpEntity requestEntity = new StringEntity( otherFieldsObject.toString( ), ContentType.APPLICATION_JSON ); request.setEntity( requestEntity ); final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
/** * send current ip to server */ private String ipSend() throws Exception { HttpClient ip_send = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/UploadIP"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id))); params.add(new BasicNameValuePair("ip", ip)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = ip_send.execute(post); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int ip_save = jsonObject.getInt("ip_save"); if (ip_save == 1) { return "SUCCESS"; } else return "FAIL"; } return "401 UNAUTHORIZED"; }
/** * Performs HTTP Post request with OAuth authentication for the endpoint * with the given path, with the given binary bodies as payload. Uses * multipart/mixed content type. * * @param path * the path to be called. * @param binaryBodies * the payload. * @return the CloseableHttpResponse object. * @throws ClientProtocolException * @throws IOException */ CloseableHttpResponse executeHttpPost(String path, List<BinaryBody> binaryBodies) throws ClientProtocolException, IOException { logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path); HttpPost httpPost = createHttpPost(baseUri + path); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MULTIPART_MIXED_BOUNDARY); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (BinaryBody binaryBody : binaryBodies) { multipartEntityBuilder.addBinaryBody(binaryBody.getBinaryBodyName(), binaryBody.getFileStream(), ContentType.create(binaryBody.getMediaType()), binaryBody.getFileName()); } HttpEntity httpEntity = multipartEntityBuilder.setBoundary(OpenApisEndpoint.BOUNDARY).build(); httpPost.setEntity(httpEntity); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path); return response; }
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception { start(); try { SystemDefaultHttpClient httpClient = getHttpClient(); doHttpClientRequest(httpClient, new HttpGet(getBaseURL())); // Always do a GET before POST to trigger the SPNego negotiation if (doPost) { HttpPost post = new HttpPost(getBaseURL()); byte [] postBytes = POST.getBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(postBytes); InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length); // Important that the entity is not repeatable -- this means if // we have to renegotiate (e.g. b/c the cookie wasn't handled properly) // the test will fail. Assert.assertFalse(entity.isRepeatable()); post.setEntity(entity); doHttpClientRequest(httpClient, post); } } finally { stop(); } }
/** * Implemented createPOST from Interface interfaceAPI (see for more details) * * @param message * Message, which should be posted. * @throws UnsupportedEncodingException * if text is not in Unicode */ public void createPOST(String message) throws UnsupportedEncodingException { httpclient = HttpClients.createDefault(); httppost = new HttpPost(Configuration.meaningcloudApiUri); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(3); params.add(new BasicNameValuePair("txt", message)); params.add(new BasicNameValuePair("key", apiKey)); params.add(new BasicNameValuePair("of", outputMode)); params.add(new BasicNameValuePair("lang", lang)); params.add(new BasicNameValuePair("tt", topictypes)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); }
@Test public void testDeleteQueue() throws IOException { String queueName = "testDeleteQueue"; // Create a queue to delete. QueueCreateRequest request = new QueueCreateRequest() .name(queueName).durable(false).autoDelete(false); HttpPost httpPost = new HttpPost(apiBasePath + "/queues"); String value = objectMapper.writeValueAsString(request); StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); CloseableHttpResponse response = client.execute(httpPost); Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED); // Delete the queue. HttpDelete httpDelete = new HttpDelete(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/" + queueName); response = client.execute(httpDelete); Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK); }
public static String submitOrderRequest(Ticket ticket, TrainQuery query) { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.submitOrderRequest); httpPost.addHeader(CookieManager.cookieHeader()); String param = genSubmitOrderRequestParam(ticket, query); httpPost.setEntity(new StringEntity(param, 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; }
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; }
public static String getQueueCount(Ticket ticket, TrainQuery query) { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.getQueueCount); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity(getQueueCountParam(ticket, 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("getQueueCount error", e); } return result; }
/** * 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); }
public static HttpPost post(String url, String body) { StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8); entity.setContentType(ContentType.APPLICATION_JSON.toString()); HttpPost req = new HttpPost(url); req.setEntity(entity); return req; }
private void createTestDB() { HttpClient hc = getHttpClient(); HttpPost post = new HttpPost(QUERY_URL); HttpResponse response = null; try { List<NameValuePair> nameValues = new ArrayList<NameValuePair>(); String createSql = "CREATE DATABASE " + DB_NAME; NameValuePair nameValue = new BasicNameValuePair("q", createSql); nameValues.add(nameValue); HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8"); post.setEntity(entity); response = hc.execute(post); closeHttpClient(hc); // System.out.println(response); } catch (Exception e) { e.printStackTrace(); }finally{ closeResponse(response); closeHttpClient(hc); } }
public JweToken fetchJweToken(String googleIdToken) throws IOException { CsrfToken csrfToken; HttpGet csrfRequest = new HttpGet(k8sClusterEndpoint + "/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/api/v1/csrftoken/login"); csrfRequest.setHeader(HttpHeaders.AUTHORIZATION, BEARER_PREFIX + googleIdToken); try (CloseableHttpResponse csrfResponse = httpClient.execute(csrfRequest)) { csrfToken = objectMapper.readValue(csrfResponse.getEntity().getContent(), CsrfToken.class); } HttpPost jweRequest = new HttpPost(k8sClusterEndpoint + "/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/api/v1/login"); jweRequest.setHeader(HttpHeaders.AUTHORIZATION, BEARER_PREFIX + googleIdToken); jweRequest.setHeader("x-csrf-token", csrfToken.getToken()); jweRequest.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); jweRequest.setEntity(new StringEntity(objectMapper.writeValueAsString(new JweTokenRequestBody().withToken(googleIdToken)))); try (CloseableHttpResponse jweResponse = httpClient.execute(jweRequest)) { JweToken jweToken = objectMapper.readValue(IOUtils.toString(jweResponse.getEntity().getContent(), StandardCharsets.UTF_8), JweToken.class); jweToken.setEncodedJweToken(URLEncoder.encode(jweToken.getJweToken(), StandardCharsets.UTF_8.toString())); return jweToken; } }
public HttpClient post(String body) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(url); HttpEntity entity = new StringEntity(body, Charsets.UTF_8); httpPost.setEntity(entity); httpRequest = httpPost; return this; }
@Override public Boolean execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); httpPost.setConfig(config); } Map<String, String> params = new HashMap<>(); params.put("media_id", materialId); httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); try(CloseableHttpResponse response = httpclient.execute(httpPost)){ String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } else { return true; } }finally { httpPost.releaseConnection(); } }
/** * Sends request to NGB server, retrieves an authorization token and adds it to an input request. * This is required for secure requests. * @param request to authorize */ protected void addAuthorizationToRequest(HttpRequestBase request) { try { HttpPost post = new HttpPost(serverParameters.getServerUrl() + serverParameters.getAuthenticationUrl()); StringEntity input = new StringEntity(serverParameters.getAuthPayload()); input.setContentType(APPLICATION_JSON); post.setEntity(input); post.setHeader(CACHE_CONTROL, CACHE_CONTROL_NO_CACHE); post.setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded"); String result = RequestManager.executeRequest(post); Authentication authentication = getMapper().readValue(result, Authentication.class); request.setHeader("authorization", "Bearer " + authentication.getAccessToken()); } catch (IOException e) { throw new ApplicationException("Failed to authenticate request", e); } }
public static Future<HttpResponse> POST(String url, FutureCallback<HttpResponse> callback, List<NameValuePair> params, String encoding, Map<String, String> headers) { HttpPost post = new HttpPost(url); headers.forEach((key, value) -> { post.setHeader(key, value); }); HttpEntity entity = new UrlEncodedFormEntity(params, HttpClientUtil.getEncode(encoding)); post.setEntity(entity); return HTTP_CLIENT.execute(post, callback); }
@Override public void run() { try { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 500); HttpConnectionParams.setSoTimeout(httpParams, 500); HttpClient httpclient = new DefaultHttpClient(httpParams); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("latitude", "" + latitude)); params.add(new BasicNameValuePair("longitude", "" + longitude)); params.add(new BasicNameValuePair("userid", userId)); //服务器地址,指向Servlet HttpPost httpPost = new HttpPost(ServerUtil.SLUpdateLocation); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");//以UTF-8格式发送 httpPost.setEntity(entity); //对提交数据进行编码 httpclient.execute(httpPost); } catch (Exception e) { } }
private void setupMultipartEntity(HttpPost httpPost){ if(isDebug){ log("Request upload file:"+mFile.getName() +" exists:"+ mFile.exists()); } MultipartEntityBuilder entity = MultipartEntityBuilder.create() .seContentType(ContentType.MULTIPART_FORM_DATA) .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody(mName,mFile,ContentType.DEFAULT_BINARY,mFileName) //uploadFile对应服务端类的同名属性<File类型> .setCharset(DEFAULT_CHARSET); for (String key:mFileParames.keySet()) { String value = mFileParames.get(key); entity.addTextBody(key,value); } httpPost.setEntity(entity.build()); }
/** * {@inheritDoc} */ @Override public HttpRequestBase getRequest(SipProfile acc) throws IOException { String requestURL = "https://samurai.sipgate.net/RPC2"; HttpPost httpPost = new HttpPost(requestURL); // TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it String userpassword = acc.username + ":" + acc.data; String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() ); httpPost.addHeader("Authorization", "Basic " + encodedAuthorization); httpPost.addHeader("Content-Type", "text/xml"); // prepare POST body String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>"; // set POST body HttpEntity entity = new StringEntity(body); httpPost.setEntity(entity); return httpPost; }
private String postAndGetReply(URL url, String body) throws IOException { String responseString = null; try (GeoEventHttpClient http = httpClientService.createNewClient()) { HttpPost postRequest = http.createPostRequest(url, body, "application/json;charset=UTF-8"); postRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml"); postRequest.addHeader("Cookie", token); //postRequest.addHeader("Content Type","application/json;charset=UTF-8"); responseString = http.executeAndReturnBody(postRequest, GeoEventHttpClient.DEFAULT_TIMEOUT); } catch (Exception e) { LOGGER.debug(e.getMessage()); } return responseString; }
public String executeOn(String ip) throws IOException, SonosControllerException { String uri = "http://" + ip + ":" + SOAP_PORT + this.endpoint; HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "text/xml"); request.setHeader("SOAPACTION", this.service + "#" + this.action); String content = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"" + " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body>" + "<u:" + this.action + " xmlns:u=\"" + this.service + "\">" + this.getBody() + "</u:" + this.action + ">" + "</s:Body></s:Envelope>"; HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8")); request.setEntity(entity); HttpResponse response = getHttpClient().execute(request); String responseString = EntityUtils.toString(response.getEntity()); this.handleError(ip, responseString); return responseString; }
@Override public T execute() throws ClientProtocolException, IOException { HttpPost post = new HttpPost(InstagramConstants.apiUrl + getUrl()); post.addHeader("Connection", "close"); post.addHeader("Accept", "*/*"); post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); post.addHeader("Cookie2", "$Version=1"); post.addHeader("Accept-Language", "en-US"); post.addHeader("User-Agent", InstagramConstants.userAgent); String parsedData = InstagramHashing.generateSignature(getPayload()); post.setEntity(new StringEntity(parsedData)); HttpResponse response = InstagramContextHolder.getContext().getHttpClient().execute(post); int resultCode = response.getStatusLine().getStatusCode(); String content = EntityUtils.toString(response.getEntity()); post.releaseConnection(); return parseResult(resultCode, content); }
/** * Posts static data, either as image or as file * * @param content the content * @param isImage indicates whether this is an image or a file * @return request object to check status codes and return values */ public Response postStaticData( final byte[ ] content, final boolean isImage ) { final HttpPost request = new HttpPost( this.yambasBase + "apps/" + this.appName + "/data/" + ( isImage ? "images/" : "files/" ) ); request.setEntity( EntityBuilder.create( ).setBinary( content ).build( ) ); request.addHeader( "Content-Type", "application/octet-stream" ); request.addHeader( "x-apiomat-apikey", this.apiKey ); request.addHeader( "x-apiomat-system", this.system.toString( ) ); try { final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
/** * 向目标url发送post请求 * * @author sheefee * @date 2017年9月12日 下午5:10:36 * @param url * @param params * @return boolean */ public static boolean post(String url, Map<String, String> params) { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 参数处理 if (params != null && !params.isEmpty()) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Iterator<Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); } // 执行请求 try { CloseableHttpResponse response = httpclient.execute(httpPost); response.getStatusLine().getStatusCode(); } catch (Exception e) { e.printStackTrace(); } return true; }
/** * Http POST 字符串 * @param host * @param path * @param connectTimeout * @param headers * @param querys * @param body * @param signHeaderPrefixList * @param appKey * @param appSecret * @return * @throws Exception */ public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret) throws Exception { headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret); HttpClient httpClient = wrapClient(host); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout)); HttpPost post = new HttpPost(initUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue())); } if (StringUtils.isNotBlank(body)) { post.setEntity(new StringEntity(body, Constants.ENCODING)); } return convert(httpClient.execute(post)); }
/** * Invokes a method from the Telegram API. * * @param method the method * @param <T> the return type * @return the object returned from the method invocation * @throws IOException when an I/O Exception occurs during the method * invocation * @throws TelegramException when the method invocation returns an error * @throws JsonParseException when the object returned is unknown */ public <T extends Serializable> T execute(TelegramMethod<T> method) throws IOException { Objects.requireNonNull(method, "method cannot be null!"); HttpPost httpPost = new HttpPost(API_URL + token + '/' + method.getName()); httpPost.setEntity(method.getHttpEntity()); try (CloseableHttpResponse response = httpClient.execute(httpPost); InputStreamReader reader = new InputStreamReader(response.getEntity().getContent()); BufferedReader bufferedReader = new BufferedReader(reader); JsonReader json = new JsonReader(bufferedReader)) { JsonElement src = Streams.parse(json); Type typeOfT = $Gson$Types.newParameterizedTypeWithOwner(null, Result.class, method.getReturnType(src)); Result<T> result = TelegramObject.gson.fromJson(src, typeOfT); if (!result.ok()) { throw result.toException(); } return result.get(); } catch (JsonParseException e) { throw new IOException(e); } }
@Test public void testbrokenLink() throws IOException, URISyntaxException { JSONObject object = new JSONObject(); object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO"); object.put("marketName", "eoemarket"); object.put("count", 1); JSONArray data = new JSONArray(); JSONObject o = new JSONObject(); o.put("id", -1); o.put("link", "http://testsssssss"); o.put("statusCode", 404); data.add(o); object.put("data", data); Reader input = new StringReader(object.toJSONString()); byte[] binaryData = IOUtils.toByteArray(input, "UTF-8"); String encodeBase64 = Base64.encodeBase64String(binaryData); String url = "http://localhost:8080/sjk-market/market/brokenLink.d"; url = "http://app-t.sjk.ijinshan.com/market/brokenLink.d"; URIBuilder builder = new URIBuilder(url); builder.setParameter("c", encodeBase64); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(builder.build()); HttpResponse response = httpclient.execute(httpPost); logger.debug("URI: {} , {}", url, response.getStatusLine()); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); // be convinient to debug String rspJSON = IOUtils.toString(is, "UTF-8"); System.out.println(rspJSON); }
private void executePostRequest(CloseableHttpClient client, HttpPost loginHttpPost) throws QGException { try { client.execute(loginHttpPost); } catch (IOException e) { throw new QGException("POST execution error", e); } }