简体   繁体   中英

Android - Post XML schema to PHP server API

I'm trying to parse out an XML schema to my server.

URL obj = new URL(url);
URLConnection uc = obj.openConnection();
HttpURLConnection conn = (HttpURLConnection) uc;
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", Integer.toString(filecontent.length())); 
conn.setRequestProperty("Content-Encoding", "gzip");

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(filecontent);
writer.close();

where filecontent is my XML schema in a String format. If I try to read the response of my server with

BufferedReader in = new BufferedReader(new 
InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null ) {
     response.append(inputLine);
    }
in.close();

my app will hang and EVENTUALLY, it'll be able to finish but the response will be empty. Not parsing/writing any content will allow me to read the response of the server and it won't hang. The view is in XML which gives me a XML Parse Error with an EXCEPTION in CDATA: exception 'Exception' with message 'String could not be parsed as XML'.

I have a C# version of the code that works for sure and comparing my Java code with the C# code, it looks quite similar except for one thing: C# writes out an XmlDocument for the content with XmlWriter for the writer which I don't believe Java is capable of doing. I can paste the C# code here if needed.

Anyone know whats wrong? Its either the format of the XML schema is wrong so the server isn't accepting it or that it doesn't accept strings? Or perhaps it isn't equivalent to the C# code? I'm at a loss as to the reason why its not working, any help would be appreciated.

"where filecontent is my XML schema in a String format" - implies your data is uncompressed text, but you tell the server it is encoded with gzip on this line --

conn.setRequestProperty("Content-Encoding", "gzip");

The server is likely trying to un-zip your string and ending up in a confused state. Try removing that line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM