1、(401) 未经授权;
解决方法:将用户名密码加密后,添加到HTTP HEADER中。
String auth = "ZRFC" + ":" + "Init1234";
String encodeAuth = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8)));
connection.setRequestProperty("Authorization", encodeAuth);
2、POST方法地址;
解决方法:要先用GET方法从去调用ODATA中GET_ENTIY方法,例如:http://vhcals4h.com:44301/sap/opu/odata/sap/ztest_srv/HEADERSet('5000000001'),然后再将返回内容作为表身,传到ENTITYSET地址,如:http://vhcals4h.com:44301/sap/opu/odata/sap/ztest_srv/HEADERSet('5000000001')。
3、CSRF跨域问题;
解决方法:先用GET方法取到TOKEN再放到POST HEADER中。
String csrfToken = connection.getHeaderField("X-CSRF-Token");
connPost.setRequestProperty("X-CSRF-Token", csrfToken);
package odata_test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; public class RestfulAction { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //添加cookie支持 CookieManager manager = new CookieManager(); //设置cookie策略,只接受与你对话服务器的cookie,而不接收Internet上其它服务器发送的cookie manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); CookieHandler.setDefault(manager); System.out.println(manager.getCookieStore()); String url = "http://vhcals4h.com:44301/sap/opu/odata/sap/ztest_srv/HEADERSet('5000000001')"; URL serverUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection(); connection.setRequestMethod("GET"); //connection.setRequestProperty("Authorization", "Basic cmF5bW9uZDpJbml0MTIzNA=="); String auth = "ZRFC" + ":" + "Init1234"; String encodeAuth = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8))); connection.setRequestProperty("Authorization", encodeAuth); connection.setRequestProperty("X-CSRF-Token", "Fetch"); if (connection.getResponseCode() != 200) { throw new RuntimeException( "HTTP GET Request Failed with Error code : " + connection.getResponseCode()); } // BufferedReader responseBuffer = new BufferedReader( // new InputStreamReader((connection.getInputStream()))); // String output; // System.out.println("Output from Server: \n"); // while ((output = responseBuffer.readLine()) != null) { // System.out.println(output); // } //解析XML DocumentBuilderFactory bbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = bbf.newDocumentBuilder(); Document doc = builder.parse(connection.getInputStream()); //Document doc = builder.parse("src/test.xml"); Element root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); if (nodes != null) { for ( int i = 0; i < nodes.getLength(); i++ ) { Node node = nodes.item(i); // TEXT_NODE 说明该节点是文本节点 // ELEMENT_NODE 说明该节点是个元素节点 if (node.getNodeType() == Node.ELEMENT_NODE) { // (7)取得节点的属性值 // String email = user.getAttributes() // .getNamedItem("email").getNodeValue(); // System.out.println(email); // 注意,节点的属性也是它的子节点。它的节点类型也是Node.ELEMENT_NODE // (8)轮循子节点 for (Node subnode = node.getFirstChild(); subnode != null; subnode = subnode.getNextSibling()) { if (subnode.getNodeType() == Node.ELEMENT_NODE) { } // System.out.println("nodeName:" + subnode.getNodeType()); // System.out.println("nodeName:" + subnode.getNodeName()); // System.out.println("nodeVaule:" + subnode.getNodeValue()); } } } } // for( int i = 0; i < nodes.getLength(); i++ ) { // Node node = nodes.item(i); // System.out.println(node.getNodeValue()); // } NodeList belnr = root.getElementsByTagName("d:BELNR"); belnr.item(0).getFirstChild().setNodeValue("510000"); System.out.println(belnr.item(0).getFirstChild().getNodeValue()); System.out.println(doc.toString()); //保存xml文件 TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource domSource=new DOMSource(doc); //设置编码类型 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //转换成xml文件 StreamResult result=new StreamResult(new FileOutputStream("src/new.xml")); //StreamResult result=new StreamResult(); transformer.transform(domSource, result); //转换成字符串 StringWriter strWriter = new StringWriter(); StreamResult resultStr = new StreamResult(strWriter); transformer.transform(domSource, resultStr); String requestBody = strWriter.getBuffer().toString(); System.out.println(requestBody); //String cookie = connection.getHeaderField("Cookie"); String csrfToken = connection.getHeaderField("X-CSRF-Token"); System.out.println(manager.getCookieStore()); connection.disconnect(); //POST方法 HttpURLConnection connPost = (HttpURLConnection) new URL("http://vhcals4h.com:44301/sap/opu/odata/sap/ztest_srv/HEADERSet").openConnection(); connPost.setRequestMethod("POST"); connPost.setRequestProperty("Authorization", encodeAuth); connPost.setRequestProperty("X-CSRF-Token", csrfToken); connPost.setRequestProperty("Content-Type", "application/xml"); //connPost.setRequestProperty("Cookie", cookie); connPost.setDoOutput(true); connPost.setDoInput(true); connPost.setUseCaches(false); connPost.setRequestProperty("Connection","Keep-Alive"); OutputStream outStream = connPost.getOutputStream(); outStream.write(requestBody.getBytes()); outStream.flush(); outStream.close(); System.out.println(connPost.getResponseCode()); connPost.disconnect(); } }
4、403错误;
解决方法:添加Cookie支持。
//添加cookie支持
CookieManager manager = new CookieManager();
//设置cookie策略,只接受与你对话服务器的cookie,而不接收Internet上其它服务器发送的cookie
manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(manager);
System.out.println(manager.getCookieStore());
另外还涉及到一些XML解析,以下为完整代码,包含GET和POST方法: