类似于"curl / grep"的Java代码



在终端中,如果我使用命令,

curl -u username:passw -v https://example.com/rest/prototype/1/content/123456 | grep VALUE-I-WANT

返回我想要的值。如何在Java中复制这一点?

最简单的方法是使用Runtime.getRuntime.exec()

例如,要获取Windows上默认浏览器的注册表值:

String command = "curl -u username:passw -v https://example.com/rest/prototype/1/content/123456 | grep VALUE-I-WANT";
try
{
    Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
    e.printStackTrace();
}

然后使用Scanner来获得命令的输出,如果需要的话。

Scanner kb = new Scanner(process.getInputStream());

注意: String中的转义字符,必须转义才能正常工作。此外,这只是一个参考帮助,而不是预先煮熟的实际解决方案。

或者除了上面的答案,如果你想使用Http客户端点击url,然后解析数据得到结果http://www.mkyong.com/java/apache-httpclient-examples/

好的是,如果你想有帖子点击/请求,你可以很容易地做到

对于post你可以有一个像

这样的方法
public Map<String, String> postData(String url, Map<String, String> headerMap, Map<String, String> formMap) throws IOException {
        CustomRedirectStratergy customRedirectStratergy = new CustomRedirectStratergy();
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = new HttpPost(url);
        StringBuilder builder = null;
//        LOGGER.info("hiturl {} ",url);
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
//                LOGGER.info("headers ---- {}, {}",entry.getKey(), entry.getValue());
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        if (formMap != null) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : formMap.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
            UrlEncodedFormEntity form = new UrlEncodedFormEntity(nameValuePairs);
            httpPost.setEntity(form);
        }
        httpClient = HttpClientBuilder.create().
                setRedirectStrategy(customRedirectStratergy).
                setDefaultRequestConfig(globalConfig).
                setDefaultCookieStore(cookieStore).
                build();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        Charset charset = ContentType.getOrDefault(httpEntity).getCharset();
        if (charset == null) {
            charset = StandardCharsets.UTF_8;
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put(CLIENT_RESPOSNE, EntityUtils.toString(response.getEntity(), charset));
        resultMap.put(LAST_REDIRECT, customRedirectStratergy.getRedirectionLocation());
        return resultMap;
    }

很明显,你需要重写customredirectstrategy来获取是否有重定向。

然后使用任何解析器(可能是JSOUP解析器)来做您喜欢的

最新更新