public static String checkRandCodeAnsyn(String randCode) { Objects.requireNonNull(randCode); ResultManager.touch(randCode, "confirmRandCode"); CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.checkRandCodeAnsyn); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity(checkRandCodeAnsynParam(), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))); String result = StringUtils.EMPTY; try (CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); logger.debug(result); } catch (IOException e) { logger.error("checkRandCodeAnsyn error", e); } return result; }
/** * 报工 * */ 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; }
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; }
public static String uamtk() { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.uamtk); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity("appid=otn", 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("tk", "newapptk")); } catch (IOException e) { logger.error("uamtk error", e); } return result; }
public static String authClient() { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.authClient); httpPost.addHeader(CookieManager.cookieHeader()); String param = Optional.ofNullable(ResultManager.get("tk")).map(r -> null == r.getValue() ? StringUtils.EMPTY : r.getValue().toString()).orElse(StringUtils.EMPTY); httpPost.setEntity(new StringEntity("tk=" + 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); } catch (IOException e) { logger.error("authClient error", e); } return result; }
public static String submitOrderRequest(Ticket ticket, TrainQuery query) { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.submitOrderRequest); httpPost.addHeader(CookieManager.cookieHeader()); String param = genSubmitOrderRequestParam(ticket, query); httpPost.setEntity(new StringEntity(param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { logger.error("checkUser error", e); } return result; }
public static String checkOrderInfo(TrainQuery query) { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { logger.error("checkUser error", e); } return result; }
public static String getQueueCount(Ticket ticket, TrainQuery query) { CloseableHttpClient httpClient = buildHttpClient(); HttpPost httpPost = new HttpPost(UrlConfig.getQueueCount); httpPost.addHeader(CookieManager.cookieHeader()); httpPost.setEntity(new StringEntity(getQueueCountParam(ticket, query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpPost)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { logger.error("getQueueCount error", e); } return result; }
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; }
/** * 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; }
@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(); }
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; }
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; }
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(); } }
/** * 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(); }
/** * 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; }
/** * 登陆报工系统 */ 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; }
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; }
/** * 向目标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; }
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); }
@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")); }
@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); } }
@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); }
/** * 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(); }
@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)); }
@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()); } }
@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); } } }
@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()); } }
@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()); }
@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()); } }
@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); } }
@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()); }
@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()); }
@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()); }
@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; }
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); } }
/** * 商户处理支付结果通知后同步返回给微信参数 * * @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, "支付结果通知同步返回失败"); } }
/** * 使用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; }
/** * 发送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; }
/** * post 请求 * * @param url * @param data * @return */ private static String httpPost(String url, String data) { try { HttpEntity entity = Request.Post(url).bodyString(data, 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; }