0

我是一个直接的新手。经过 2 周的研究,我已经到了这一点,仍然非常迷茫和绝望。

我的目标:从 EnergyStar Portfolio Manager Restful Web 服务/API 中检索数据,并将该数据放入 SQL 数据库或 Excel 工作表中。

到目前为止的进展:1)我找到了一个示例代码,它似乎很适合我的需要,除了身份验证部分。我在让 WSDL 服务工作方面比 RESTful 服务更成功。特别是对于 EnergySTAR,需要某种身份验证,我似乎无法解决。

2)检索GET协议:http: //portfoliomanager.energystar.gov/webservices/home/test/api/reporting/designMetrics/get

我的源代码:

package com;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
 
import com.User;
 
@Path("/wstest/property/")
public class UserManagementModule
{
    @GET
    @Path("/{propertyId}/design/metrics?measurementSystem=METRIC")
    @Produces("application/xml")
    public Response getUserById(@PathParam("propertyId") Integer id)
    
    {
        User user = new User();
        user.setId(id);
        return Response.status(200).entity(user).build();
    }
    
 
    
}
package com;
 
import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "propertyMetrics")
public class User implements Serializable {
 
    private static final long serialVersionUID = 1L;
      
    @XmlAttribute(name = "propertyId")
    private int propertyId;
    
    @XmlElement(name="metric")
    private double metric;
    
    @XmlAttribute(name = "designEnergyCost")
    private double designEnergyCost;
       
    @XmlAttribute(name = "designScore")
    private double designScore; 
    
    @XmlAttribute(name = "designSiteTotal")
    private double designSiteTotal;
    
    @XmlAttribute(name = "designSiteIntensity")
    private double designSiteIntensity;
    
    @XmlAttribute(name = "designTargetEnergyCost")
    private double designTargetEnergyCost;
    
    @XmlAttribute(name = "designTargetTotalGHGEmissions")
    private double designTargetTotalGHGEmissions;
    
    @XmlAttribute(name = "designTargetSiteTotal")
    private double designTargetSiteTotal;
 
    @XmlAttribute(name = "designTargetSiteIntensity")
    private double designTargetSiteIntensity;
    
    @XmlAttribute(name = "designTargetSourceTotal")
    private double designTargetSourceTotal;
    
    @XmlAttribute(name = "designTargetSourceIntensity")
    private double designTargetSourceIntensity;
    
    @XmlAttribute(name = "medianEnergyCost")
    private double medianEnergyCost;
    
    @XmlAttribute(name = "medianTotalGHGEmissions")
    private double medianTotalGHGEmissions;
    
    @XmlAttribute(name = "medianScore")
    private double medianScore;
     
    public int getId() {
        return propertyId;
    }
    public void setId(int propertyId) {
        this.propertyId = propertyId;
    }
  
public double getmendianScore() {
return medianScore;
}
//    
//    public void setFirstName(String firstName) {
//        this.firstName = firstName;
//    }
//    public String getLastName() {
//        return lastName;
//    }
//    public void setLastName(String lastName) {
//        this.lastName = lastName;
//    }
}
package tests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.User; 

public class RestClientXML {

	public static void main(String[] args) 
    {
        try
        {
            URL url = new URL(" https://portfoliomanager.energystar.gov/wstest/");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/xml");
 
            if (conn.getResponseCode() != 200) 
            {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }
 
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String apiOutput = br.readLine();
            System.out.println(apiOutput);
            conn.disconnect();
 
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
 
            System.out.println(user.getId());
            
/*            System.out.println(user.getFirstName());
            System.out.println(user.getLastName());
             */
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

我知道有一些身份验证需要用户名和密码,所以我也尝试了这个而不是 RestClient 类,但都不起作用。

public static void main(String[] args) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;

        try {

            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost("https://portfoliomanager.energystar.gov/wstest/");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("content-type", "application/xml"));

             StringEntity input = new StringEntity("{\"username\": \"yungv1\",\"password\": \"dummypassword\"}");
             input.setContentType("application/xml");
             httpPost.setEntity(input);

            for (NameValuePair h : nvps)
            {
                httpPost.addHeader(h.getName(), h.getValue());
            }

            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            
        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            try{
                response.close();
                httpClient.close();
            }catch(Exception ex) {
                ex.printStackTrace();
            }
        }

我知道这很草率。您能否指出我如何实现目标的方向?

我也尝试运行它,并不断收到 401 错误,我认为这是身份验证失败。我不知道还有什么方法可以解决这部分问题,以及是否还有更多需要研究的东西。

4

1 回答 1

0
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String((getWebServicesUsername() + ":" + getWebServicesPassword()).getBytes()));

其中 conn 是 HttpURLConnection。

于 2015-03-25T19:11:49.800 回答