【问题标题】:How to use httpClient to filer parts of an xml file in Java如何使用 httpClient 在 Java 中过滤部分 xml 文件
【发布时间】:2025-12-02 11:20:12
【问题描述】:

我目前正在做一个项目,我必须从代​​谢物数据库 PubChem 请求数据。我正在使用 Apache 的 HttpClient。我正在执行以下操作:

HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
    + cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
HttpEntity entity = response.getEntity();
pubChemInchi = EntityUtils.toString(entity);

问题在于这段代码流式传输整个 XML 文件:

<?xml version="1.0"?>
<PC-Compound
xmlns="http://www.ncbi.nlm.nih.gov"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="http://www.ncbi.nlm.nih.gov ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem.xsd">

等等

我想要的是我可以请求,例如,PubChem ID,它将粘贴与该 ID 对应的值。我发现这可以使用本机 Java 方法来完成,但我需要为此使用 HttpClient。 使用本机 Java,可以这样完成:

cid = 5282253
reader = new PCCompoundXMLReader(
new URL("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=" + cid + "&disopt=SaveXML").newInputStream())
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")

(注意:这段代码是用 Groovy 编写的,但经过一些调整后它也可以在 Java 中运行)

所以,如果有人可以帮助我,那就太好了:)

【问题讨论】:

    标签: java xml httpclient pubchem


    【解决方案1】:

    有多种方法可以做到这一点。

    如果您想将响应转换为 bean,并且不希望响应的结构发生变化,我会考虑使用 XStream。 另一种选择是直接使用 SAX 解析器。

    当然,快速而肮脏的方法是将您的响应内容转换为 bufferedReader。然后将该阅读器提供给您正在使用的 XMLReader。

    使用您上面的代码的示例是:

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
        + cid + "&disopt=SaveXML");
    pubChemRequest.getAllHeaders();
    System.out.println(pubChemRequest);
    HttpResponse response = null;
    response = httpclient.execute(pubChemRequest);
    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
    cid = 5282253
    reader = new PCCompoundXMLReader(br)
    mol = reader.read(new NNMolecule())
    println "CID: " + mol.getProperty("PubChem CID")
    

    搜索 RESTful Web 服务客户端或 XMLReaders 应该会为您提供有关此主题的更多信息

    【讨论】:

      【解决方案2】:

      尝试使用 NameValuePair

      例如:

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      
      nameValuePairs.add(new BasicNameValuePair("username", user123));
      
      nameValuePairs.add(new BasicNameValuePair("password", pass123));
      
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      
      HttpResponse response = httpclient.execute(httppost);
      

      【讨论】: