я следующий метод, который вызывает службу POST и возвращает XML, который я хочу поставить атрибуты элемента в HashMapКак я могу очистить следующий метод POST JAVA
Формат 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();
}
}
заранее спасибо, ребята.
Спасибо, это здорово. Я прочитаю о рефаторировании метода извлечения – robert