Java Code Examples for org.apache.http.client.methods.HttpPost

The following are top voted examples for showing how to use org.apache.http.client.methods.HttpPost. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: open-kilda   File: Mininet.java   View source code 11 votes vote down vote up
/**
 * 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;
}
 
Example 2
Project: sjk   File: CatalogConvertorControllerTest.java   View source code 8 votes vote down vote up
@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());
}
 
Example 3
Project: Thrush   File: HttpRequest.java   View source code 8 votes vote down vote up
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;
}
 
Example 4
Project: elasticjob-oray-client   File: HttpUtils.java   View source code 8 votes vote down vote up
/**
 * 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);
}
 
Example 5
Project: CSipSimple   File: Sipgate.java   View source code 8 votes vote down vote up
/**
 * {@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;
}
 
Example 6
Project: restheart-java-client   File: HttpConnectionUtils.java   View source code 8 votes vote down vote up
@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;
}
 
Example 7
Project: Sem-Update   File: VentanaPrincipal.java   View source code 7 votes vote down vote up
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:?]");
    }
 
Example 8
Project: Reer   File: HttpClientConfigurer.java   View source code 7 votes vote down vote up
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);
            }
        }
 
Example 9
Project: CTQS   File: HttpClientUtil.java   View source code 7 votes vote down vote up
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();
    }

}
 
Example 10
Project: hadoop   File: AuthenticatorTestCase.java   View source code 7 votes vote down vote up
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();
  }
}
 
Example 11
Project: elasticjob-stock-push   File: HttpUtils.java   View source code 7 votes vote down vote up
/**
 * 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);
}
 
Example 12
Project: datarouter   File: DatarouterHttpRequest.java   View source code 7 votes vote down vote up
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);
	}
}
 
Example 13
Project: boohee_v5.6   File: q.java   View source code 6 votes vote down vote up
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;
}
 
Example 14
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: Higher-Cloud-Computing-Project   File: ServerUtil.java   View source code 6 votes vote down vote up
/**
 * 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";
}
 
Example 16
Project: keywordEntityApiRankService   File: MeaningCloudAPI.java   View source code 6 votes vote down vote up
/**
 * 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"));

}
 
Example 17
Project: message-broker   File: QueuesRestApiTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 18
Project: Cryptocurrency-Java-Wrappers   File: GoogleTrends.java   View source code 6 votes vote down vote up
/**
 * 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);

}
 
Example 19
Project: mxisd   File: RestClientUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 20
Project: k8s-proxy   File: JweTokenRetriever.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 21
Project: flow-platform   File: HttpClient.java   View source code 6 votes vote down vote up
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;
}
 
Example 22
Project: Wechat-Group   File: MaterialDeleteRequestExecutor.java   View source code 6 votes vote down vote up
@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();
  }
}
 
Example 23
Project: NGB-master   File: AbstractHTTPCommandHandler.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 24
Project: wechat-mall   File: AsynHttpClient.java   View source code 6 votes vote down vote up
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);
}
 
Example 25
Project: DaiGo   File: LocationService.java   View source code 6 votes vote down vote up
@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) {

    }
}
 
Example 26
Project: QuickHttp   File: QuickHttpController.java   View source code 6 votes vote down vote up
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());
}
 
Example 27
Project: defense-solutions-proofs-of-concept   File: MLOBIOutboundTransport.java   View source code 6 votes vote down vote up
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;
}
 
Example 28
Project: sonos-remote-things   File: CommandBuilder.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: RoboInsta   File: InstagramPostRequest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 30
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 31
Project: simple-sso   File: HTTPUtil.java   View source code 6 votes vote down vote up
/**
 * 向目标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;
}
 
Example 32
Project: FaceDistinguish   File: HttpUtil.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 33
Project: Telejam   File: TelegramConnection.java   View source code 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 34
Project: sjk   File: ControllerTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 35
Project: sonar-quality-gates-plugin   File: SonarHttpRequester.java   View source code 5 votes vote down vote up
private void executePostRequest(CloseableHttpClient client, HttpPost loginHttpPost) throws QGException {

        try {
            client.execute(loginHttpPost);
        } catch (IOException e) {
            throw new QGException("POST execution error", e);
        }
    }
 
Example 36
Project: GitHub   File: HttpClientStackTest.java   View source code 5 votes vote down vote up
@Test public void createPostRequest() throws Exception {
    TestRequest.Post request = new TestRequest.Post();
    assertEquals(request.getMethod(), Method.POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example 37
Project: spring-cloud-samples   File: ApplicationTests.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClientBuilder builder = HttpClientBuilder.create();
//		HttpPost post = new HttpPost("http://localhost:8088/refresh");
		HttpPost post = new HttpPost("http://localhost:8888/bus/refresh");
		CloseableHttpResponse response = builder.build().execute(post);
		System.out.println(EntityUtils.toString(response.getEntity()));
	}
 
Example 38
Project: FCat   File: HttpCallSSL.java   View source code 5 votes vote down vote up
@Override
public HttpCallObj getResponse(String apiUrl, String method, Map<String, String> parameMap) throws IOException {
	HttpCallObj result = new HttpCallObj();
	if (parameMap != null) {
		StringBuilder urlParame = new StringBuilder();
		Iterator<String> parameKey = parameMap.keySet().iterator();
		while (parameKey.hasNext()) {
			String parameName = parameKey.next();
			String parameVal = parameMap.get(parameName);
			if (!StrUtil.isBlank(parameVal)) {
				urlParame.append(parameName);
				urlParame.append("=");
				urlParame.append(parameVal);
				urlParame.append("&");
			}
		}
		if (urlParame.length() > 0) {
			if (urlParame.lastIndexOf("&") == urlParame.length() - 1) {
				urlParame.deleteCharAt(urlParame.length() - 1);
			}
			if (apiUrl.indexOf("?") != -1) {
				apiUrl += "&" + urlParame.toString();
			} else {
				apiUrl += "?" + urlParame.toString();
			}
		}
	}
	if (method != null && "POST".equals(method.toUpperCase())) {
		HttpPost httpPost = getHttpPost();
		result = responseBytes(getPostResponse(apiUrl, httpPost));
		httpPost.releaseConnection();
	} else {
		HttpGet httpGet = getHttpGet();
		result = responseBytes(getGetResponse(apiUrl, httpGet));
		httpGet.releaseConnection();
	}
	return result;
}
 
Example 39
Project: asura   File: AsuraCommonsHttpclient.java   View source code 5 votes vote down vote up
private void handlerParam(Map<String, String> param, HttpPost httpPost) throws UnsupportedEncodingException {
    if (Check.isNullOrEmpty(param)) {
        return;
    }
    Iterator<String> iterator = param.keySet().iterator();
    List<NameValuePair> nvps = new ArrayList<>(param.size());
    while (iterator.hasNext()) {
        String paramName = iterator.next();
        nvps.add(new BasicNameValuePair(paramName, param.get(paramName)));
    }
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
}
 
Example 40
Project: GitHub   File: OkApacheClientTest.java   View source code 5 votes vote down vote up
@Test public void postEmptyEntity() throws Exception {
  server.enqueue(new MockResponse());
  final HttpPost post = new HttpPost(server.url("/").url().toURI());
  client.execute(post);

  RecordedRequest request = server.takeRequest();
  assertEquals(0, request.getBodySize());
  assertNotNull(request.getBody());
}