Java Code Examples for org.apache.http.Consts

The following are top voted examples for showing how to use org.apache.http.Consts. 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: 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 2
Project: Thrush   File: HttpRequest.java   View source code 7 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 3
Project: elasticsearch_my   File: RestClientSingleHostIntegTests.java   View source code 7 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    StringBuilder body = new StringBuilder();
    try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) {
        char[] buffer = new char[256];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            body.append(buffer, 0, read);
        }
    }
    Headers requestHeaders = httpExchange.getRequestHeaders();
    Headers responseHeaders = httpExchange.getResponseHeaders();
    for (Map.Entry<String, List<String>> header : requestHeaders.entrySet()) {
        responseHeaders.put(header.getKey(), header.getValue());
    }
    httpExchange.getRequestBody().close();
    httpExchange.sendResponseHeaders(statusCode, body.length() == 0 ? -1 : body.length());
    if (body.length() > 0) {
        try (OutputStream out = httpExchange.getResponseBody()) {
            out.write(body.toString().getBytes(Consts.UTF_8));
        }
    }
    httpExchange.close();
}
 
Example 4
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 5
Project: dcits-report   File: UserService.java   View source code 7 votes vote down vote up
/**
 * 报工
 * 
 */
public boolean report() {
	HttpPost post = new HttpPost(Api.reportUrl);
	try {
		post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
		HttpResponse resp = client.execute(post);
		JSONObject jo = JSONObject.parseObject(EntityUtils.toString(resp.getEntity()));
		// 报工成功,返回json结构的报文{"data" : [ {},{}...],"success" : true}
		if (jo.getBooleanValue("success")) {
			return true;
		}
		logger.warn(jo.getString("error"));
	} catch (Exception e) {
		logger.error("报工异常:", e);
	}
	return false;
}
 
Example 6
Project: Thrush   File: HttpRequest.java   View source code 6 votes vote down vote up
public static String confirmSingleForQueue(Ticket ticket, TrainQuery query) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.confirmSingleForQueue);

    httpPost.addHeader(CookieManager.cookieHeader());
    httpPost.setEntity(new StringEntity(confirmSingleForQueueParam(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("confirmSingleForQueue error", e);
    }

    return result;
}
 
Example 7
Project: framework   File: PayManager.java   View source code 6 votes vote down vote up
/**
 * post 请求
 *
 * @param url
 * @param xml
 * @return
 */
private static String post(String url, String xml) {
	try {
		HttpEntity entity = Request.Post(url).bodyString(xml, ContentType.create("text/xml", Consts.UTF_8.name())).execute().returnResponse().getEntity();
		if (entity != null) {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			entity.writeTo(byteArrayOutputStream);
			return byteArrayOutputStream.toString(Consts.UTF_8.name());
		}
		return null;
	} catch (Exception e) {
		logger.error("post请求异常," + e.getMessage() + "\npost url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
Example 8
Project: poloniex-api-java   File: HTTPClient.java   View source code 6 votes vote down vote up
public String postHttp(String url, List<NameValuePair> params, List<NameValuePair> headers) throws IOException
{
    HttpPost post = new HttpPost(url);
    post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
    post.getEntity().toString();

    if (headers != null)
    {
        for (NameValuePair header : headers)
        {
            post.addHeader(header.getName(), header.getValue());
        }
    }

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(post);

    HttpEntity entity = response.getEntity();
    if (entity != null)
    {
        return EntityUtils.toString(entity);

    }
    return null;
}
 
Example 9
Project: chatbot   File: QANARY.java   View source code 6 votes vote down vote up
private String makeRequest(String question) {
        try {
            HttpPost httpPost = new HttpPost(URL);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("query", question));
//            params.add(new BasicNameValuePair("lang", "it"));
            params.add(new BasicNameValuePair("kb", "dbpedia"));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);

            // Error Scenario
            if(response.getStatusLine().getStatusCode() >= 400) {
                logger.error("QANARY Server could not answer due to: " + response.getStatusLine());
                return null;
            }

            return EntityUtils.toString(response.getEntity());
        }
        catch(Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
 
Example 10
Project: lams   File: URLEncodedUtils.java   View source code 6 votes vote down vote up
/**
 * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an
 * {@link HttpEntity}. The encoding is taken from the entity's
 * Content-Encoding header.
 * <p>
 * This is typically used while parsing an HTTP POST.
 *
 * @param entity
 *            The entity to parse
 * @throws IOException
 *             If there was an exception getting the entity's data.
 */
public static List <NameValuePair> parse (
        final HttpEntity entity) throws IOException {
    ContentType contentType = ContentType.get(entity);
    if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) {
        String content = EntityUtils.toString(entity, Consts.ASCII);
        if (content != null && content.length() > 0) {
            Charset charset = contentType.getCharset();
            if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
            }
            return parse(content, charset);
        }
    }
    return Collections.emptyList();
}
 
Example 11
Project: xrd4j   File: AbstractBodyHandler.java   View source code 6 votes vote down vote up
/**
 * Builds a new StringEntity object that's used as HTTP 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. If the given request body is null or empty, null is returned.
 *
 * @param requestBody request body
 * @param headers HTTP headers to be added to the request
 * @return new StringEntity object or null
 */
protected StringEntity buildRequestEntity(String requestBody, Map<String, String> headers) {
    String contentTypeHeader = "Content-Type";
    LOGGER.debug("Build new request entity.");

    // If request body is not null or empty
    if (requestBody != null && !requestBody.isEmpty()) {
        LOGGER.debug("Request body found.");
        // Set content type of the request, default is "application/xml"
        String reqContentType = "application/xml";
        if (headers != null && !headers.isEmpty()) {
            if (headers.get(contentTypeHeader) != null && !headers.get(contentTypeHeader).isEmpty()) {
                reqContentType = headers.get(contentTypeHeader);
            } else {
                LOGGER.warn("\"Content-Type\" header is missing. Use \"application/xml\" as default.");
                // No value set, use default value
                headers.put(contentTypeHeader, reqContentType);
            }
        }
        // Create request entity that's used as request body
        return new StringEntity(requestBody, ContentType.create(reqContentType, Consts.UTF_8));
    }
    LOGGER.debug("No request body found for request. Null is returned");
    return null;
}
 
Example 12
Project: dcits-report   File: UserService.java   View source code 6 votes vote down vote up
/**
 * 登陆报工系统
 */
public boolean login() {
	HttpPost post = new HttpPost(Api.loginUrl);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("username", SessionUtil.getUsername()));
	params.add(new BasicNameValuePair("password", SessionUtil.getPassword()));
	try {
		post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
		HttpResponse resp = client.execute(post);// 登陆
		String charset = HttpHeaderUtil.getResponseCharset(resp);
		String respHtml = StringUtil.removeEmptyLine(resp.getEntity().getContent(), charset == null ? "utf-8" : charset);

		Document doc = Jsoup.parse(respHtml);
		Elements titles = doc.getElementsByTag("TITLE");
		for (Element title : titles) {
			if (title.hasText() && title.text().contains("Success")) {
				return true;// 登陆成功
			}
		}
	} catch (Exception e) {
		logger.error("登陆失败:", e);
	}
	return false;
}
 
Example 13
Project: datax   File: HttpClientUtil.java   View source code 6 votes vote down vote up
public String executeAndGet(HttpRequestBase httpRequestBase) throws Exception {
    HttpResponse response;
    String entiStr = "";
    try {
        response = httpClient.execute(httpRequestBase);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            System.err.println("请求地址:" + httpRequestBase.getURI() + ", 请求方法:" + httpRequestBase.getMethod()
                    + ",STATUS CODE = " + response.getStatusLine().getStatusCode());
            if (httpRequestBase != null) {
                httpRequestBase.abort();
            }
            throw new Exception("Response Status Code : " + response.getStatusLine().getStatusCode());
        } else {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entiStr = EntityUtils.toString(entity, Consts.UTF_8);
            } else {
                throw new Exception("Response Entity Is Null");
            }
        }
    } catch (Exception e) {
        throw e;
    }

    return entiStr;
}
 
Example 14
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 15
Project: yinuo-tcp   File: BaseClient.java   View source code 6 votes vote down vote up
public String post(String url, String jsonIn) throws IOException, InvalidHttpResponseStatusException {
    HttpPost request = new HttpPost(url);
    request.setHeader("User-Agent", getUserAgent());
    request.setHeader("Content-Type", CONTENT_TYPE);
    if (getCredentials() != null) {
        request.setHeader("Authorization", getCredentials());
    }

    if (StringUtils.isBlank(jsonIn)) {
        return service(request);
    }
    StringEntity stringEntity = new StringEntity(jsonIn, Consts.UTF_8);
    stringEntity.setContentType(CONTENT_TYPE);
    request.setEntity(stringEntity);

    return service(request);
}
 
Example 16
Project: purecloud-iot   File: TestRFC2617Scheme.java   View source code 6 votes vote down vote up
@Test
public void testSerialization() throws Exception {
    final Header challenge = new BasicHeader(AUTH.WWW_AUTH, "test realm=\"test\", blah=blah, yada=\"yada yada\"");

    final TestAuthScheme testScheme = new TestAuthScheme(Consts.ISO_8859_1);
    testScheme.processChallenge(challenge);

    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(buffer);
    out.writeObject(testScheme);
    out.flush();
    final byte[] raw = buffer.toByteArray();
    final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw));
    final TestAuthScheme authScheme = (TestAuthScheme) in.readObject();

    Assert.assertEquals(Consts.ISO_8859_1, authScheme.getCredentialsCharset());
    Assert.assertEquals("test", authScheme.getParameter("realm"));
    Assert.assertEquals("blah", authScheme.getParameter("blah"));
    Assert.assertEquals("yada yada", authScheme.getParameter("yada"));
}
 
Example 17
Project: axon-eventstore   File: EsWriterDefaultImpl.java   View source code 6 votes vote down vote up
@Override
public void createLinkedProjection(String host, String projectionName, String... includedStreams) {
   final String url = host + "/projections/continuous?name=" + projectionName + "&emit=yes&checkpoints=yes&enabled=yes";
   try {
      try {
         final HttpPost post = new HttpPost(url);
         post.addHeader(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON);
         post.setEntity(new StringEntity(getProjectionForStreams(includedStreams), ContentType.create(CONTENT_TYPE_JSON_EVENTS, Consts.UTF_8)));
         LOGGER.info("Executing request " + post.getRequestLine());
         final CloseableHttpResponse response = httpclient.execute(post);
         try {
            if (HttpStatus.SC_NO_CONTENT != response.getStatusLine()
                  .getStatusCode()) {
               throw new RuntimeException("Could not delete stream with url: " + url);
            }
         } finally {
            response.close();
         }
      } finally {
         httpclient.close();
      }
   } catch (final IOException e) {
      throw new RuntimeException("Could not delete stream with url: " + url, e);
   }
}
 
Example 18
Project: purecloud-iot   File: TestDecompressingEntity.java   View source code 6 votes vote down vote up
@Test
public void testStreaming() throws Exception {
    final CRC32 crc32 = new CRC32();
    final ByteArrayInputStream in = new ByteArrayInputStream("1234567890".getBytes(Consts.ASCII));
    final InputStreamEntity wrapped = new InputStreamEntity(in, -1);
    final ChecksumEntity entity = new ChecksumEntity(wrapped, crc32);
    Assert.assertTrue(entity.isStreaming());
    final String s = EntityUtils.toString(entity);
    Assert.assertEquals("1234567890", s);
    Assert.assertEquals(639479525L, crc32.getValue());
    final InputStream in1 = entity.getContent();
    final InputStream in2 = entity.getContent();
    Assert.assertTrue(in1 == in2);
    EntityUtils.consume(entity);
    EntityUtils.consume(entity);
}
 
Example 19
Project: remote-files-sync   File: URLEncodedUtilsHC4.java   View source code 6 votes vote down vote up
/**
 * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an {@link HttpEntity}. The encoding is
 * taken from the entity's Content-Encoding header.
 * <p>
 * This is typically used while parsing an HTTP POST.
 *
 * @param entity
 *            The entity to parse
 * @return a list of {@link NameValuePair} as built from the URI's query portion.
 * @throws IOException
 *             If there was an exception getting the entity's data.
 */
public static List <NameValuePair> parse(
        final HttpEntity entity) throws IOException {
    final ContentType contentType = ContentType.get(entity);
    if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) {
        final String content = EntityUtilsHC4.toString(entity, Consts.ASCII);
        if (content != null && content.length() > 0) {
            Charset charset = contentType.getCharset();
            if (charset == null) {
                charset = Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET);
            }
            return parse(content, charset, QP_SEPS);
        }
    }
    return Collections.emptyList();
}
 
Example 20
Project: purecloud-iot   File: TestDeflate.java   View source code 6 votes vote down vote up
@Test
public void testCompressDecompress() throws Exception {

    final String s = "some kind of text";
    final byte[] input = s.getBytes(Consts.ASCII);

    // Compress the bytes
    final byte[] compressed = new byte[input.length * 2];
    final Deflater compresser = new Deflater();
    compresser.setInput(input);
    compresser.finish();
    final int len = compresser.deflate(compressed);

    final HttpEntity entity = new DeflateDecompressingEntity(new ByteArrayEntity(compressed, 0, len));
    Assert.assertEquals(s, EntityUtils.toString(entity));
}
 
Example 21
Project: LiteGraph   File: GremlinServerHttpIntegrateTest.java   View source code 6 votes vote down vote up
@Test
@Deprecated
public void should200OnPOSTWithAuthorizationHeaderOld() throws Exception {
    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpPost httppost = new HttpPost("http://localhost:8182");
    httppost.addHeader("Content-Type", "application/json");
    httppost.addHeader("Authorization", "Basic " + encoder.encodeToString("stephen:password".getBytes()));
    httppost.setEntity(new StringEntity("{\"gremlin\":\"1-1\"}", Consts.UTF_8));

    try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/json", response.getEntity().getContentType().getValue());
        final String json = EntityUtils.toString(response.getEntity());
        final JsonNode node = mapper.readTree(json);
        assertEquals(0, node.get("result").get("data").get(0).intValue());
    }
}
 
Example 22
Project: purecloud-iot   File: TestClientReauthentication.java   View source code 6 votes vote down vote up
@Override
public void handle(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {
    final String creds = (String) context.getAttribute("creds");
    if (creds == null || !creds.equals("test:test")) {
        response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
    } else {
        // Make client re-authenticate on each fourth request
        if (this.count.incrementAndGet() % 4 == 0) {
            response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
        } else {
            response.setStatusCode(HttpStatus.SC_OK);
            final StringEntity entity = new StringEntity("success", Consts.ASCII);
            response.setEntity(entity);
        }
    }
}
 
Example 23
Project: LiteGraph   File: GremlinServerHttpIntegrateTest.java   View source code 6 votes vote down vote up
@Test
public void should200OnPOSTWithGremlinJsonEndcodedBodyAndArrayBindings() throws Exception {
    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpPost httppost = new HttpPost("http://localhost:8182");
    httppost.addHeader("Content-Type", "application/json");
    httppost.setEntity(new StringEntity("{\"gremlin\":\"x\", \"bindings\":{\"x\":[1,2,3]}}", Consts.UTF_8));

    try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/json", response.getEntity().getContentType().getValue());
        final String json = EntityUtils.toString(response.getEntity());
        final JsonNode node = mapper.readTree(json);
        assertEquals(true, node.get("result").get("data").isArray());
        assertEquals(1, node.get("result").get("data").get(0).intValue());
        assertEquals(2, node.get("result").get("data").get(1).intValue());
        assertEquals(3, node.get("result").get("data").get(2).intValue());
    }
}
 
Example 24
Project: purecloud-iot   File: TestMultipartEntityBuilder.java   View source code 6 votes vote down vote up
@Test
public void testMultipartCustomContentTypeParameterOverrides() throws Exception {
    final MultipartFormEntity entity = MultipartEntityBuilder.create()
            .setContentType(ContentType.MULTIPART_FORM_DATA.withParameters(
                    new BasicNameValuePair("boundary", "yada-yada"),
                    new BasicNameValuePair("charset", "ascii"),
                    new BasicNameValuePair("my", "stuff")))
            .setBoundary("blah-blah")
            .setCharset(Consts.UTF_8)
            .setLaxMode()
            .buildEntity();
    Assert.assertNotNull(entity);
    final Header contentType = entity.getContentType();
    Assert.assertNotNull(contentType);
    Assert.assertEquals("multipart/form-data; boundary=blah-blah; charset=UTF-8; my=stuff",
            contentType.getValue());
}
 
Example 25
Project: LiteGraph   File: GremlinServerHttpIntegrateTest.java   View source code 6 votes vote down vote up
@Test
public void should200OnPOSTWithAnyAcceptHeaderDefaultResultToJson() throws Exception {
    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpPost httppost = new HttpPost("http://localhost:8182");
    httppost.addHeader("Content-Type", "application/json");
    httppost.addHeader("Accept", "*/*");
    httppost.setEntity(new StringEntity("{\"gremlin\":\"1-1\"}", Consts.UTF_8));

    try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/json", response.getEntity().getContentType().getValue());
        final String json = EntityUtils.toString(response.getEntity());
        final JsonNode node = mapper.readTree(json);
        assertEquals(0, node.get("result").get("data").get(0).asInt());
    }
}
 
Example 26
Project: EEWReciever   File: SeismicObservationPoints.java   View source code 6 votes vote down vote up
@Override
public void run() {
	JsonReader jr = null;
	try {
		final HttpGet get = new HttpGet(JSON_PATH);
		final HttpResponse res = Downloader.downloader.getClient().execute(get);

		jr = new JsonReader(new InputStreamReader(res.getEntity().getContent(), Consts.UTF_8));

		final PointsJson json = gson.fromJson(jr, PointsJson.class);
		this.callback.onDone(json);
	} catch (final Exception e) {
		this.callback.onError(e);
	} finally {
		IOUtils.closeQuietly(jr);
	}
}
 
Example 27
Project: purecloud-iot   File: TestMultipartContentBody.java   View source code 6 votes vote down vote up
@Test
public void testInputStreamBody() throws Exception {
    final byte[] stuff = "Stuff".getBytes(Consts.ASCII);
    final InputStreamBody b1 = new InputStreamBody(new ByteArrayInputStream(stuff), "stuff");
    Assert.assertEquals(-1, b1.getContentLength());

    Assert.assertNull(b1.getCharset());
    Assert.assertEquals("stuff", b1.getFilename());
    Assert.assertEquals("application/octet-stream", b1.getMimeType());
    Assert.assertEquals("application", b1.getMediaType());
    Assert.assertEquals("octet-stream", b1.getSubType());

    Assert.assertEquals(MIME.ENC_BINARY, b1.getTransferEncoding());

    final InputStreamBody b2 = new InputStreamBody(
            new ByteArrayInputStream(stuff), ContentType.create("some/stuff"), "stuff");
    Assert.assertEquals(-1, b2.getContentLength());
    Assert.assertNull(b2.getCharset());
    Assert.assertEquals("stuff", b2.getFilename());
    Assert.assertEquals("some/stuff", b2.getMimeType());
    Assert.assertEquals("some", b2.getMediaType());
    Assert.assertEquals("stuff", b2.getSubType());

    Assert.assertEquals(MIME.ENC_BINARY, b2.getTransferEncoding());
}
 
Example 28
Project: purecloud-iot   File: TestPublicSuffixListParser.java   View source code 6 votes vote down vote up
@Test
public void testParse() throws Exception {
    final ClassLoader classLoader = getClass().getClassLoader();
    final InputStream in = classLoader.getResourceAsStream("suffixlist.txt");
    Assert.assertNotNull(in);
    final PublicSuffixList suffixList;
    try {
        final PublicSuffixListParser parser = new PublicSuffixListParser();
        suffixList = parser.parse(new InputStreamReader(in, Consts.UTF_8));
    } finally {
        in.close();
    }
    Assert.assertNotNull(suffixList);
    Assert.assertEquals(Arrays.asList("jp", "ac.jp", "*.tokyo.jp", "no", "h\u00E5.no"), suffixList.getRules());
    Assert.assertEquals(Arrays.asList("metro.tokyo.jp"), suffixList.getExceptions());
}
 
Example 29
Project: purecloud-iot   File: TestBasicScheme.java   View source code 6 votes vote down vote up
@Test
public void testBasicAuthenticationWith88591Chars() throws Exception {
    final int[] germanChars = { 0xE4, 0x2D, 0xF6, 0x2D, 0xFc };
    final StringBuilder buffer = new StringBuilder();
    for (final int germanChar : germanChars) {
        buffer.append((char)germanChar);
    }

    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("dh", buffer.toString());
    final BasicScheme authscheme = new BasicScheme(Consts.ISO_8859_1);

    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final HttpContext context = new BasicHttpContext();
    final Header header = authscheme.authenticate(creds, request, context);
    Assert.assertEquals("Basic ZGg65C32Lfw=", header.getValue());
}
 
Example 30
Project: clouddisk   File: UserCheckLoginParser.java   View source code 6 votes vote down vote up
@Override
public HttpPost initRequest(final UserCheckLoginParameter userCheckLoginParameter) {
	setBinaryFilename(LoginConst.USER_INFO_PATH_NAME);
	Login login = readObjForDisk(Login.class);
	if(null==login){
		login = new Login();
	}
	final HttpPost request = new HttpPost(CONST.URI_PATH);
	final List<NameValuePair> data = new ArrayList<>();
	data.add(new BasicNameValuePair(CONST.QID_NAME, login.getQid()));
	data.add(new BasicNameValuePair(CONST.METHOD_KEY, CONST.METHOD_VAL));
	data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL));
	data.add(new BasicNameValuePair("t", TimeUtil.getTimeLenth(13)));
	request.setConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.NETSCAPE).build());
	request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));
	return request;
}
 
Example 31
Project: Thrush   File: HttpRequest.java   View source code 5 votes vote down vote up
public static void checkRandCode(String randCode) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.checkCode);

    httpPost.addHeader(CookieManager.cookieHeader());
    httpPost.setEntity(new StringEntity("answer=" + encode(randCode) + "&login_site=E&&rand=sjrand", ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
        logger.debug(EntityUtils.toString(response.getEntity()));
    } catch (IOException e) {
        logger.error("checkRandCode error", e);
    }
}
 
Example 32
Project: framework   File: PayManager.java   View source code 5 votes vote down vote up
/**
 * 商户处理支付结果通知后同步返回给微信参数
 *
 * @param servletResponse
 * @param postData
 * @throws PayApiException
 */
private static void responseToWechat(ServletResponse servletResponse, String postData) throws PayApiException {
	try {
		servletResponse.getOutputStream().write(postData.getBytes(Consts.UTF_8));
		servletResponse.getOutputStream().flush();
		servletResponse.getOutputStream().close();
	} catch (IOException e) {
		throw new PayApiException(PayCode.FAIL, "支付结果通知同步返回失败");
	}
}
 
Example 33
Project: framework   File: OAuthManager.java   View source code 5 votes vote down vote up
/**
 * 使用UTF-8进行URL编码
 *
 * @param str
 * @return
 */
private static String urlEncode(String str) {
	String result = null;
	try {
		result = URLEncoder.encode(str, Consts.UTF_8.name());
	} catch (UnsupportedEncodingException e) {
		// never throws
	}
	return result;
}
 
Example 34
Project: framework   File: HttpUtils.java   View source code 5 votes vote down vote up
/**
 * 发送http post请求
 *
 * @param url      url
 * @param instream post数据的字节流
 * @return
 */
public static String post(String url, InputStream instream) {
	try {
		HttpEntity entity = Request.Post(url).bodyStream(instream, ContentType.create("text/html", Consts.UTF_8)).execute().returnResponse().getEntity();
		return entity != null ? EntityUtils.toString(entity) : null;
	} catch (Exception e) {
		logger.error("post请求异常," + e.getMessage() + "\n post url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
Example 35
Project: elasticsearch_my   File: ElasticsearchHostsSnifferTests.java   View source code 5 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    if (httpExchange.getRequestMethod().equals(HttpGet.METHOD_NAME)) {
        if (httpExchange.getRequestURI().getRawQuery().equals("timeout=" + sniffTimeoutMillis + "ms")) {
            String nodesInfoBody = sniffResponse.nodesInfoBody;
            httpExchange.sendResponseHeaders(sniffResponse.nodesInfoResponseCode, nodesInfoBody.length());
            try (OutputStream out = httpExchange.getResponseBody()) {
                out.write(nodesInfoBody.getBytes(Consts.UTF_8));
                return;
            }
        }
    }
    httpExchange.sendResponseHeaders(404, 0);
    httpExchange.close();
}
 
Example 36
Project: css-elasticsearch   File: HttpUtil.java   View source code 5 votes vote down vote up
/**
 * @param url 请求URL
 * @param method 请求URL
 * @param param	json参数(post|put)
 * @param auth	认证(username+:+password)
 * @return 返回结果
 */
public static String urlRequest(String url,String method,String param,String auth){
	String result = null;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(60*1000);
		connection.setRequestMethod(method.toUpperCase());
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		if(param!=null&&!"".equals(param)){
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.write(param.getBytes(Consts.UTF_8));
			dos.flush();
			dos.close();
		}else{
			connection.connect();
		}
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK||connection.getResponseCode()==HttpURLConnection.HTTP_CREATED){
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=in.read(buff, 0, buff.length))>0){
				out.write(buff, 0, len);
			}
			byte[] data = out.toByteArray();
			in.close();
			result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
		}else{
			result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--http request error !",e);
	}
	return result;
}
 
Example 37
Project: css-elasticsearch   File: HttpUtil.java   View source code 5 votes vote down vote up
/**
 * <pre>
 * 描述: URL编码
 * @author yi.zhang
 * 时间: 2017年9月15日 下午3:33:38
 * @param target 目标字符串
 * @return 
 * </pre>
 */
public static String encode(String target){
	String result = target;
	try {
		result = URLEncoder.encode(target, Consts.UTF_8.name());
	} catch (UnsupportedEncodingException e) {
		logger.error("--http encode error !",e);
	}
	return result;
}
 
Example 38
Project: css-elasticsearch   File: HttpUtil.java   View source code 5 votes vote down vote up
/**
 * <pre>
 * 描述: URL解码
 * @author yi.zhang
 * 时间: 2017年9月15日 下午3:33:38
 * @param target 目标字符串
 * @return 
 * </pre>
 */
public static String decode(String target){
	String result = target;
	try {
		result = URLDecoder.decode(target, Consts.UTF_8.name());
	} catch (UnsupportedEncodingException e) {
		logger.error("--http decode error !",e);
	}
	return result;
}
 
Example 39
Project: chatbot   File: GenesisService.java   View source code 5 votes vote down vote up
private String makeRequest(String endpoint, String uri, String requestType) {
    try {
        HttpPost httpPost = new HttpPost(endpoint);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("url", uri));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);

        String result = null;
        String entities = EntityUtils.toString(response.getEntity());
        JsonNode rootNode = new ObjectMapper().readTree(entities).get(requestType);

        switch (requestType) {
            case "similarEntities":
            case "relatedEntities":
                int count = 0;
                result = "";
                for (JsonNode node : rootNode) {
                    count++;
                    if (count <= ResponseData.MAX_DATA_SIZE) {
                        result += "<" + node.get("url").getTextValue() + "> ";
                    }
                    else {
                        break;
                    }
                }
                break;
            case "summary":
                result = rootNode.getTextValue();
                break;
        }
        return result.trim();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 40
Project: Wechat-Group   File: WxMpPayServiceImpl.java   View source code 5 votes vote down vote up
private String executeWithKey(String url, String requestStr) throws WxErrorException {
  try {
    SSLContext sslContext = getConfig().getSslContext();
    if (null == sslContext) {
      throw new IllegalArgumentException("请先初始化配置类(即WxMpConfigStorage的实现类)中的SSLContext!");
    }

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null,
      new DefaultHostnameVerifier());

    HttpPost httpPost = new HttpPost(url);
    if (this.wxMpService.getHttpProxy() != null) {
      httpPost.setConfig(RequestConfig.custom().setProxy(this.wxMpService.getHttpProxy()).build());
    }

    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).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;
      }
    } finally {
      httpPost.releaseConnection();
    }
  } catch (Exception 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);
  }
}