Skip to content

Instantly share code, notes, and snippets.

@mapiondev
Created June 9, 2010 09:02
Show Gist options
  • Save mapiondev/431247 to your computer and use it in GitHub Desktop.
Save mapiondev/431247 to your computer and use it in GitHub Desktop.
[java] Web APIをJAXBで取得するためのクラス
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class WebAPI {
private URL url;
private Map<String, String> headers = new HashMap<String, String>();
private int timeout;
public WebAPI() {
}
public WebAPI(URL url) {
this.url = url;
}
public void setHeader(String key, String value) {
headers.put(key, value);
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
@SuppressWarnings("unchecked")
public <T> T request(Class<T> clazz) {
InputStream inputStream = null;
try {
URLConnection connection = url.openConnection();
connection.setReadTimeout(timeout);
for (Map.Entry<String, String> e : headers.entrySet()) {
connection.setRequestProperty(e.getKey(), e.getValue());
}
inputStream = connection.getInputStream();
JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object obj = unmarshaller.unmarshal(inputStream);
return (T) obj;
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// public static void main(String[] args) throws Exception {
// WebAPI api = new WebAPI(new URL("http://zip.cgis.biz/xml/zip.php?zn=1080023"));
// ZIPResult result = api.request(ZIPResult.class);
// System.out.println(result.getResult().get(0).getName()); // ZipSearchXML
// System.out.println(result.getResult().get(1).getVersion()); // 1.01
// }
}
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<!-- 簡単のため全ては書いてませんが、name, version取るだけならこれでok -->
<xsd:element name="ZIP_result">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="result" type="result" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="result">
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="name" type="xsd:string"/>
<xsd:attribute name="version" type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:schema>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment