Java Code Examples for org.apache.http.entity.StringEntity

The following are top voted examples for showing how to use org.apache.http.entity.StringEntity. 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: safecharge-java   File: SafechargeRequestExecutor.java   View source code 12 votes vote down vote up
/**
 * Sends a POST request to the service at {@code serviceUrl} with a payload of {@code request}.
 * The request type is determined by the {@code headers} param.
 *
 * @param request    A {@link String} representation of a request object. Can be JSON object, form data, etc...
 * @param serviceUrl The service URL to sent the request to
 * @param headers    An array of {@link Header} objects, used to determine the request type
 * @return {@link String} response from the service (representing JSON object)
 * @throws IOException if the connection is interrupted or the response is unparsable
 */
public String executeRequest(String request, String serviceUrl, Header[] headers) throws IOException {
    HttpPost httpPost = new HttpPost(serviceUrl);
    httpPost.setHeaders(headers);
    httpPost.setEntity(new StringEntity(request, Charset.forName("UTF-8")));

    if (logger.isDebugEnabled()) {
        logger.debug("Sent " + request);
    }

    HttpResponse response = httpClient.execute(httpPost);

    String responseJSON = EntityUtils.toString(response.getEntity(), UTF8_CHARSET);
    if (logger.isDebugEnabled()) {
        logger.debug("Received " + responseJSON);
    }
    return responseJSON;
}
 
Example 2
Project: raven   File: IOSCustomizedcast.java   View source code 11 votes vote down vote up
public String uploadContents(String contents) throws Exception {
	if (!rootJson.has("appkey") || !rootJson.has("timestamp") || !rootJson.has("validation_token")) {
		throw new Exception("appkey, timestamp and validation_token needs to be set.");
	}
	// Construct the json string
	JSONObject uploadJson = new JSONObject();
	uploadJson.put("appkey", rootJson.getString("appkey"));
	uploadJson.put("timestamp", rootJson.getString("timestamp"));
	uploadJson.put("validation_token", rootJson.getString("validation_token"));
	uploadJson.put("content", contents);
	// Construct the request
	String url = host + uploadPath;
	HttpPost post = new HttpPost(url);
	post.setHeader("User-Agent", USER_AGENT);
	StringEntity se = new StringEntity(uploadJson.toString(), "UTF-8");
	post.setEntity(se);
	// Send the post request and get the response
	HttpResponse response = client.execute(post);
	System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
	BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	StringBuffer result = new StringBuffer();
	String line = "";
	while ((line = rd.readLine()) != null) {
		result.append(line);
	}
	System.out.println(result.toString());
	// Decode response string and get file_id from it
	JSONObject respJson = new JSONObject(result.toString());
	String ret = respJson.getString("ret");
	if (!ret.equals("SUCCESS")) {
		throw new Exception("Failed to upload file");
	}
	JSONObject data = respJson.getJSONObject("data");
	String fileId = data.getString("file_id");
	// Set file_id into rootJson using setPredefinedKeyValue
	setPredefinedKeyValue("file_id", fileId);
	return fileId;
}
 
Example 3
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 4
Project: restheart-java-client   File: HttpConnectionUtils.java   View source code 10 votes vote down vote up
@Override
public <REQ> CloseableHttpResponse sendHttpPut(String url, REQ request) {
    CloseableHttpResponse execute = null;
    String requestJson = GsonUtils.toJson(request);

    try {
        LOGGER.log(Level.FINER, "Send PUT request:" + requestJson + " to url-" + url);
        HttpPut httpPut = new HttpPut(url);
        StringEntity entity = new StringEntity(requestJson, "UTF-8");
        entity.setContentType("application/json");
        httpPut.setEntity(entity);
        execute = this.httpClientFactory.getHttpClient().execute(httpPut);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Was unable to send PUT request:" + requestJson
            + " (displaying first 1000 chars) from url-" + url, e);
    }

    return execute;
}
 
Example 5
Project: weixinpay   File: HttpUtil.java   View source code 9 votes vote down vote up
public static String postUrl(String url, String body) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

    //请求超时 ,连接超时
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    //读取超时
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);


    try {
        StringEntity entity = new StringEntity(body, "UTF-8");
        httppost.setEntity(entity);

        System.out.println(entity.toString());

        HttpResponse response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String charsetName = EntityUtils.getContentCharSet(response.getEntity());
            //System.out.println(charsetName + "<<<<<<<<<<<<<<<<<");

            String rs = EntityUtils.toString(response.getEntity());
            //System.out.println( ">>>>>>" + rs);

            return rs;
        } else {
            //System.out.println("Eorr occus");
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return "";
}
 
Example 6
Project: smart_plan   File: DatabaseDataRequestHandler.java   View source code 8 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    RequestLine line = request.getRequestLine();
    Uri uri = Uri.parse(line.getUri());
    DatabaseDataEntity entity;
    if (uri != null) {
        String database = uri.getQueryParameter("database");
        String tableName = uri.getQueryParameter("table");
        entity = getDataResponse(database, tableName);
        if (entity != null) {
            response.setStatusCode(200);
            response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
            return;
        }
    }
    entity = new DatabaseDataEntity();
    entity.setDataList(new ArrayList<Map<String, String>>());
    entity.setCode(BaseEntity.FAILURE_CODE);
    response.setStatusCode(200);
    response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
 
Example 7
Project: Thrush   File: HttpRequest.java   View source code 8 votes vote down vote up
public static String login(String randCode) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.loginUrl);

    httpPost.addHeader(CookieManager.cookieHeader());
    String param = "username=" + encode(UserConfig.username) + "&password=" + encode(UserConfig.password) + "&appid=otn";
    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)) {
        result = EntityUtils.toString(response.getEntity());
        CookieManager.touch(response);
        ResultManager.touch(result, new ResultKey("uamtk", "uamtk"));
    } catch (IOException e) {
        logger.error("login error", e);
    }

    return result;
}
 
Example 8
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 9
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View source code 8 votes vote down vote up
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException {

		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));
		String  body = "{\"default-user\": \""+usr+"\"}";

		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);
		}
	}
 
Example 10
Project: saluki   File: ServiceTestController.java   View source code 8 votes vote down vote up
@RequestMapping(value = "testService", method = RequestMethod.POST)
public Object testService(@RequestParam(value = "ipPort", required = true) String ipPort,
    @RequestBody GrpcServiceTestModel model) throws Exception {
  String serviceUrl = "http://" + ipPort + "/service/test";
  HttpPost request = new HttpPost(serviceUrl);
  request.addHeader("content-type", "application/json");
  request.addHeader("Accept", "application/json");
  try {
    StringEntity entity = new StringEntity(gson.toJson(model), "utf-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    request.setEntity(entity);
    HttpResponse httpResponse = httpClient.execute(request);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      String minitorJson = EntityUtils.toString(httpResponse.getEntity());
      Object response = gson.fromJson(minitorJson, new TypeToken<Object>() {}.getType());
      return response;
    }
  } catch (Exception e) {
    throw e;
  }
  return null;
}
 
Example 11
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 12
Project: ants   File: Client.java   View source code 8 votes vote down vote up
public boolean postMessage(String url, String message) {
	boolean ret = true;
	
	try {
		CloseableHttpClient client = HttpClients.createDefault();
	    HttpPost httpPost = new HttpPost(URL + url);
	 
	    StringEntity se = new StringEntity(message);
	    
	    httpPost.setEntity(se);
	    
	    CloseableHttpResponse response = client.execute(httpPost);
	    
	    if (response.getStatusLine().getStatusCode() != 200) {
	    	ret = false;
	    }
	    
	    client.close();
	} catch (Exception e) {
		e.printStackTrace();
		ret = false;
		System.exit(-1);
	}
	
	return ret;
}
 
Example 13
Project: elasticsearch-queryexpansion-plugin   File: AbstractITCase.java   View source code 8 votes vote down vote up
/**
 * Creates the specified index in ElasticSearch
 * 
 * @param indexName
 *            the index name to augment
 * @param typeName
 *            the type name to augment
 * @param id
 *            the id of the document to add
 * @param jsonDocument
 *            the String JSON document to add
 */
protected static void createIndex(String indexName) {
	try {
		// Create our expand / search indices
		String endpoint = String.format("/%s", indexName);
		Map<String, String> params = new HashMap<String, String>();
		StringEntity requestBody = new StringEntity(INDEX_JSON);

		Response resp = client.performRequest("PUT", endpoint, params, requestBody, contentTypeHeader);
		staticLogger.debug("Response: " + resp.getStatusLine());

	} catch (IOException e) {
		// Ignore this...? probably already exists
		staticLogger.error(e.getMessage(), e);

		if (e instanceof UnsupportedEncodingException) {
			staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
			return;
		}
	}
}
 
Example 14
Project: wechat-api-java   File: HttpRequestUtil.java   View source code 8 votes vote down vote up
public static String doPost(String url, String json) throws Exception {
    try {
        CloseableHttpClient client = getHttpClient(url);
        HttpPost post = new HttpPost(url);
        config(post);
        logger.info("====> Executing request: " + post.getRequestLine());
        if (!StringUtils.isEmpty(json)) {
            StringEntity s = new StringEntity(json, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        String responseBody = client.execute(post, getStringResponseHandler());
        logger.info("====> Getting response from request " + post.getRequestLine() + " The responseBody: " + responseBody);
        return responseBody;
    } catch (Exception e) {
        if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) {
            throw new ConnectException("====> 连接服务器" + url + "失败: " + e.getMessage());
        }
        logger.error("====> HttpRequestUtil.doPost: " + e.getMessage(), e);
    }
    return null;
}
 
Example 15
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 16
Project: dhus-core   File: TestInterruptibleHttpClient.java   View source code 7 votes vote down vote up
/**
 * Starts the HTTP server.
 *
 * @return the listening port.
 */
static int start () throws IOException
{

   server = ServerBootstrap.bootstrap ().registerHandler ("*",
         new HttpRequestHandler ()
         {

            @Override
            public void handle (HttpRequest request, HttpResponse response,
                  HttpContext context)
                  throws HttpException, IOException
            {

               response.setStatusCode (HttpStatus.SC_OK);
               response.setEntity (new StringEntity ("0123456789"));
            }
         })
         .create ();
   server.start ();

   return server.getLocalPort ();
}
 
Example 17
Project: elasticsearch-queryexpansion-plugin   File: AbstractITCase.java   View source code 7 votes vote down vote up
/**
 * Adds a document to the specified ElasticSearch index / type
 * 
 * @param indexName
 *            the index name to augment
 * @param typeName
 *            the type name to augment
 * @param id
 *            the id of the document to add
 * @param jsonDocument
 *            the String JSON document to add
 */
protected static void addDocument(String indexName, String typeName, Integer id, String jsonDocument) {
	try {
		String documentEndpoint = String.format("/%s/%s/%d", indexName, typeName, id);
		StringEntity requestBody = new StringEntity(jsonDocument);
		Map<String, String> params = new HashMap<String, String>();

		Response resp = client.performRequest("PUT", documentEndpoint, params, requestBody, contentTypeHeader);
		staticLogger.debug("Response: " + resp.getStatusLine());

	} catch (IOException e) {
		// Ignore this...? probably already exists
		staticLogger.error(e.getMessage(), e);

		if (e instanceof UnsupportedEncodingException) {
			staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
			return;
		}
	}
}
 
Example 18
Project: FaceDistinguish   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 19
Project: smart_plan   File: DatabaseTableRequestHandler.java   View source code 7 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    Log.d("plan", "DatabaseTableRequestHandler");
    DatabaseEntity entity;
    String uri = request.getRequestLine().getUri();
    String key =  Uri.parse(uri).getQueryParameter("database_name");
    if (!TextUtils.isEmpty(key)) {
        entity = getTableResponse(key.trim());
    }  else {
        entity = new DatabaseEntity();
        entity.setCode(BaseEntity.FAILURE_CODE);
        entity.setDataList(new ArrayList<SimpleNameEntity>());
    }
    String result = ParserJson.getSafeJsonStr(entity);
    response.setStatusCode(200);
    response.setEntity(new StringEntity(result, "utf-8"));
}
 
Example 20
Project: integration-test-helper   File: AomHttpClient.java   View source code 7 votes vote down vote up
/**
 * Updates the module
 *
 * @param moduleName
 *        the name of the module to add
 * @param objectToUpdate
 *        JSON containing the key/value pais to use for update
 * @return request object to check status codes and return values
 */
public Response updateModule( String moduleName, JSONObject objectToUpdate )
{
	HttpPut request = new HttpPut( this.yambasBase + "modules/" + moduleName );
	setAuthorizationHeader( request );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	request.setEntity( new StringEntity( objectToUpdate.toString( ), ContentType.APPLICATION_JSON ) );

	try
	{
		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
Example 21
Project: opentest   File: HttpRequest.java   View source code 7 votes vote down vote up
public void setContent(String content, String contentType) {
    if (content == null) {
        content = "";
    }

    //TODO: Improve the validation logic
    if (contentType.indexOf('/') <= 0) {
        throw new RuntimeException(String.format("Content type \"%s\" is not a valid MIME type", contentType));
    }

    if (HttpEntityEnclosingRequestBase.class.isInstance(httpRequest)) {
        try {
            StringEntity requestEntity = new StringEntity(content);
            ((HttpEntityEnclosingRequestBase) this.httpRequest).setEntity(requestEntity);
            this.httpRequest.setHeader("Content-Type", contentType);
        } catch (Exception ex) {
            throw new RuntimeException("Failed to set HTTP request content", ex);
        }
    }
}
 
Example 22
Project: daelic   File: DruidClient.java   View source code 7 votes vote down vote up
private <REQ, RESP> RESP query(REQ request, Class<RESP> clazz) throws IOException, DruidException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(configuration.getUrl());

    StringEntity entity = new StringEntity(mapper.writeValueAsString(request), configuration.getCharset());
    httpPost.setEntity(entity);
    httpPost.setHeader("Content-type", "application/json");

    CloseableHttpResponse response = client.execute(httpPost);
    String content = EntityUtils.toString(response.getEntity(), configuration.getCharset());

    try {
        return mapper.readValue(content, clazz);
    } catch (Exception ex) {
        throw new DruidException(content);
    } finally {
        client.close();
    }
}
 
Example 23
Project: QuickHttp   File: QuickHttpController.java   View source code 7 votes vote down vote up
private void setupBodyContentFormEntity(HttpPost httpPost){
    if(isDebug){
        log("Request content: "+mBodyContent);
    }
    StringEntity entity = new StringEntity(mBodyContent,mContentType);
    httpPost.setEntity(entity);
}
 
Example 24
Project: Wechat-Group   File: MaterialNewsInfoRequestExecutor.java   View source code 7 votes vote down vote up
@Override
public WxMpMaterialNews 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 WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class);
    }
  }finally {
    httpPost.releaseConnection();
  }

}
 
Example 25
Project: teamcity-msteams-notifier   File: MsTeamsNotificationTest.java   View source code 7 votes vote down vote up
@Test
public void post_whenResponseIsFailure_logsException() throws IOException {
    ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class);
    HttpClient httpClient = mock(HttpClient.class);
    BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, ""));
    response.setEntity(new StringEntity("failure reason here"));

    when(httpClient.execute(requestCaptor.capture())).thenReturn(response);

    MsTeamsNotification w = factory.getMsTeamsNotification(httpClient);

    MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent();
    content.setBuildDescriptionWithLinkSyntax("http://foo");
    content.setCommits(new ArrayList<Commit>());

    w.setPayload(content);
    w.setEnabled(true);
    w.post();

    assertNotNull(w.getResponse());
    assertFalse(w.getResponse().getOk());
}
 
Example 26
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 7 votes vote down vote up
public void testPerformRequestOnResponseExceptionWithBrokenEntity2() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Unable to parse response body", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
    assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IllegalStateException.class));
}
 
Example 27
Project: elasticsearch_my   File: RestClientSingleHostIntegTests.java   View source code 7 votes vote down vote up
private Response bodyTest(final RestClient restClient, final String method) throws IOException {
    String requestBody = "{ \"field\": \"value\" }";
    StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
    int statusCode = randomStatusCode(getRandom());
    Response esResponse;
    try {
        esResponse = restClient.performRequest(method, "/" + statusCode, Collections.<String, String>emptyMap(), entity);
    } catch(ResponseException e) {
        esResponse = e.getResponse();
    }
    assertEquals(method, esResponse.getRequestLine().getMethod());
    assertEquals(statusCode, esResponse.getStatusLine().getStatusCode());
    assertEquals(pathPrefix + "/" + statusCode, esResponse.getRequestLine().getUri());
    assertEquals(requestBody, EntityUtils.toString(esResponse.getEntity()));

    return esResponse;
}
 
Example 28
Project: xrd4j   File: PostClient.java   View source code 7 votes vote down vote up
/**
 * Builds a new HTTP POST request with the given URL and request body.
 * Content type of the request is set according to the given headers. If the
 * given headers do not contain Content-Type header, "application/xml" is
 * used.
 *
 * @param url URL where the request is sent
 * @param requestBody request body
 * @param headers HTTP headers to be added to the request
 * @return new HttpUriRequest object
 */
@Override
protected HttpUriRequest buildtHttpRequest(String url, String requestBody, Map<String, String> headers) {
    LOGGER.debug("Build new HTTP POST request.");
    HttpUriRequest request;
    // Create request entity that's used as request body
    StringEntity requestEntity = super.buildRequestEntity(requestBody, headers);
    if (requestEntity != null) {
        request = RequestBuilder.post().setUri(url).setEntity(requestEntity).build();
    } else {
        LOGGER.debug("No request body found for HTTP POST request.");
        request = RequestBuilder.post().setUri(url).build();
    }
    // Return request
    return request;
}
 
Example 29
Project: CSipSimple   File: Mobex.java   View source code 7 votes vote down vote up
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "http://200.152.124.172/billing/webservice/Server.php";
    
    HttpPost httpPost = new HttpPost(requestURL);
    httpPost.addHeader("SOAPAction", "\"mostra_creditos\"");
    httpPost.addHeader("Content-Type", "text/xml");

    // prepare POST body
    String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " +
            "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
            "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" +
            "><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" +
            "<chave xsi:type=\"xsd:string\">" +
            acc.data +
            "</chave><username xsi:type=\"xsd:string\">" +
            acc.username.replaceAll("^12", "") +
            "</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", ""));
    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
Example 30
Project: Wechat-Group   File: WxMpPayServiceImpl.java   View source code 7 votes vote down vote up
private String executeRequest(String url, String requestStr) throws WxErrorException {
  HttpPost httpPost = new HttpPost(url);
  if (this.wxMpService.getHttpProxy() != null) {
    httpPost.setConfig(RequestConfig.custom().setProxy(this.wxMpService.getHttpProxy()).build());
  }

  try (CloseableHttpClient httpclient = HttpClients.custom().build()) {
    httpPost.setEntity(new StringEntity(new String(requestStr.getBytes("UTF-8"), "ISO-8859-1")));

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
      this.log.debug("\n[URL]:  {}\n[PARAMS]: {}\n[RESPONSE]: {}", url, requestStr, result);
      return result;
    }
  } catch (IOException e) {
    this.log.error("\n[URL]:  {}\n[PARAMS]: {}\n[EXCEPTION]: {}", url, requestStr, e.getMessage());
    throw new WxErrorException(WxError.newBuilder().setErrorCode(-1).setErrorMsg(e.getMessage()).build(), e);
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 31
Project: hustic   File: SearchRequest.java   View source code 7 votes vote down vote up
public SearchResponse execute() {
    final HttpClient client = wrapper.getHttpClient();

    SearchResponse searchResponse = null;
    try {
        final HttpPost httpPost = new HttpPost(uri);
        if (searchJson != null) {
            httpPost.setEntity(new StringEntity(searchJson.toString(),
                    ContentType.APPLICATION_JSON));
        }
        searchResponse = client.execute(httpPost, new SearchResponseHandler());
    } catch (Exception ex) {
        //Handle exception
    }
    
    return searchResponse;
}
 
Example 32
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View source code 6 votes vote down vote up
public static void associateRESTServerWithDefaultUser(String restServerName,String userName,String authType)throws Exception{
	DefaultHttpClient client = new DefaultHttpClient();

	client.getCredentialsProvider().setCredentials(
			new AuthScope(host, 8002),
			new UsernamePasswordCredentials("admin", "admin"));
	String  body = "{ \"default-user\":\""+userName+"\",\"authentication\": \""+authType+"\",\"group-name\": \"Default\"}";

	HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http");
	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);
	}
}
 
Example 33
Project: stock-api-sdk   File: HttpUtilsTest.java   View source code 6 votes vote down vote up
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_string_response_since_httpClient_execute_returned_with_success()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertEquals(response, succResponse);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
 
Example 34
Project: fpm   File: MetalinkDownloader.java   View source code 6 votes vote down vote up
private String getToken() throws IOException {
    HttpPost tokenRequest = new HttpPost("https://edelivery-ad.tomtom.com/automaticdownload/login");
    tokenRequest.setEntity(new StringEntity("user=" + login + "&password=" + password));
    log.info("Getting token");
    try (InputStream content = client.execute(tokenRequest).getEntity().getContent()) {
        return IOUtils.toString(content, "UTF-8");
    }
}
 
Example 35
Project: minsx-java-example   File: RemoteServerClientImpl.java   View source code 6 votes vote down vote up
@Test
public void testPost() throws IOException {
    String ip = "冰箱冰箱冰箱冰箱冰箱冰箱冰箱";
    // 创建HttpClientBuilder
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // HttpClient
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    // 请求参数
    StringEntity entity = new StringEntity("", DEFAULT_ENCODE);
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
    HttpPost httpPost = new HttpPost("https://m.fangliaoyun.com");
    httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
    //此处区别PC终端类型
    httpPost.addHeader("typeFlg", "9");
    //此处增加浏览器端访问IP
    httpPost.addHeader("x-forwarded-for", ip);
    httpPost.addHeader("Proxy-Client-IP", ip);
    httpPost.addHeader("WL-Proxy-Client-IP", ip);
    httpPost.addHeader("HTTP_CLIENT_IP", ip);
    httpPost.addHeader("X-Real-IP", ip);
    httpPost.addHeader("Host", ip);
    httpPost.setEntity(entity);
    httpPost.setConfig(RequestConfig.DEFAULT);

    HttpResponse httpResponse;
    // post请求
    httpResponse = closeableHttpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    System.out.println(httpEntity.getContent());
    //释放资源
    closeableHttpClient.close();
}
 
Example 36
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View source code 6 votes vote down vote up
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException
{
	try {			
		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));
		
			HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json");
			put.addHeader("Content-type", "application/json");
			put.setEntity(new StringEntity(jnode.toString()));

			HttpResponse response = client.execute(put);
			HttpEntity respEntity = response.getEntity();
			if(respEntity != null){
				String content =  EntityUtils.toString(respEntity);
				System.out.println(content);
			}
		}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}
}
 
Example 37
Project: JInsight   File: HttpAsyncClientInstrumentationTest.java   View source code 5 votes vote down vote up
@Test
public void testPost500() throws Exception {
  Snapshot expectedCounts = tracker.snapshot();
  expectedCounts.increment("POST", "500");

  HttpPost request = new HttpPost(server.getEchoEndpoint(500));
  String content = UUID.randomUUID().toString();
  request.setEntity(new StringEntity(content));
  HttpResponse response = httpclient.execute(request, null).get();
  String body = new Scanner(response.getEntity().getContent()).useDelimiter("\0").next();
  assertThat(body, CoreMatchers.containsString(content));

  debug(response);
  tracker.validate(expectedCounts);
}
 
Example 38
Project: rainbow   File: HttpUtil.java   View source code 5 votes vote down vote up
public static Object HttpPost(String aUrl, String aPostData) {
    String res = "";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpost = new HttpPost(aUrl);
    try {
        httpost.setEntity(new StringEntity(aPostData, "UTF-8"));
        HttpResponse response = httpClient.execute(httpost);
        res = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}
 
Example 39
Project: java-bitbankcc   File: Bitbankcc.java   View source code 5 votes vote down vote up
public Order sendOrder(CurrencyPair pair, BigDecimal price, BigDecimal amount, OrderSide side, OrderType type)
        throws BitbankException, IOException {
    String path = "/v1/user/spot/order";
    URIBuilder builder = getPrivateUriBuilder(path);

    String json = new OrderBody(pair, amount, price, side, type).toJson();
    StringEntity entity = new StringEntity(json);
    OrderResponse result = doHttpPost(builder, OrderResponse.class, getPrivateRequestHeader(json), entity);
    return result.data;
}
 
Example 40
Project: bootstrap   File: SessionResourceRestIT.java   View source code 5 votes vote down vote up
/**
 * No username provided gives 403
 */
@Test
public void testProtectedResourceAnonymousMeans403() throws IOException {
	final HttpPost message = new HttpPost(BASE_URI + RESOURCE);
	message.setEntity(new StringEntity("{\"id\":0}", ContentType.APPLICATION_JSON));
	final HttpResponse response = httpclient.execute(message);
	try {
		Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
	} finally {
		IOUtils.closeQuietly(response.getEntity().getContent());
	}
}