如何清理以下 POST JAVA 方法
我有以下方法,它调用 POST 服务,它返回 XML,我想将元素的属性放入 HashMap
XML 格式是:
<?xml version="1.0"?><paul><ncresponse
atA="14"
atB="10452775"
atC="0">
</ncresponse></paul>
我想要整理的方法是:
private HashMap<String, String> myMethod(URL url) throws Exception{
String dataToSend = createUrlParameters();
HttpURLConnection connection = null;
HashMap<String, String> keyValues = new HashMap<String, String>();
try {
//Create connection
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(dataToSend.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(dataToSend);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
inStream.setCharacterStream(new java.io.StringReader(response.toString()));
Document doc = dBuilder.parse(inStream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("ncresponse");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NamedNodeMap attrs = eElement.getAttributes();
int len = attrs.getLength();
for (int i=0; i<len; i++) {
Attr attr = (Attr)attrs.item(i);
//System.out.println(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
keyValues.put(attr.getNodeName(), attr.getNodeValue());
}
}
}
return keyValues;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
提前感谢大家。
I have the following method which calls a POST service and it returns XML which I want to put the attributes of the element into a HashMap
The XML format is:
<?xml version="1.0"?><paul><ncresponse
atA="14"
atB="10452775"
atC="0">
</ncresponse></paul>
The method I want to tidy up is:
private HashMap<String, String> myMethod(URL url) throws Exception{
String dataToSend = createUrlParameters();
HttpURLConnection connection = null;
HashMap<String, String> keyValues = new HashMap<String, String>();
try {
//Create connection
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(dataToSend.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(dataToSend);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
inStream.setCharacterStream(new java.io.StringReader(response.toString()));
Document doc = dBuilder.parse(inStream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("ncresponse");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NamedNodeMap attrs = eElement.getAttributes();
int len = attrs.getLength();
for (int i=0; i<len; i++) {
Attr attr = (Attr)attrs.item(i);
//System.out.println(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
keyValues.put(attr.getNodeName(), attr.getNodeValue());
}
}
}
return keyValues;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
Thanks in advance guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种方法可以简化 XML 解析。
如果您有 XML 架构,JAXB 可以进行 XML 到 Java 的转换。
您可以创建一个实用程序类,通过在构造函数中传递 XML 来解析名称值对。
与您原来的问题稍微无关,但是,如果您使用 myMethod() 连接到多个 URL,那么我会进行并行调用以加快响应速度。查看 java.util.concurrent.ScheduledExecutorService
There are two ways to simplify XML parsing.
If you have the XML schema then, JAXB can do the XML to Java conversion.
You can create a utility class to parse the name value pairs by passing it the XML in a constructor.
Slightly unrelated to your original question but, if you are using myMethod() to connect to multiple URLs then, I would make parallel calls to speed up the response. Check out java.util.concurrent.ScheduledExecutorService
首先,你的方法太长了。这可能更适合代码审查,但您必须学习如何使用提取方法重构。以下是我无意识点击几次后得到的结果:
其他更改:
First of all, your method is way too long. This probably more fits to Code Review, but you have to learn how to use Extract method refactoring. Here is what I got after few mindless clicks:
Other changes: