Android - using HttpURLConnection for POST XML data

I ran into some problem and need some help (please)!

I am very new to Android Dev (and for coding in general). Basically, I need POST XML data to be associated with the URL using HttpURLConnection, but cannot make it work. I have an application that reads and processes XML data from a GET request, but it is difficult to find the POST part.

I looked at creating a NameValuePair array, but am not sure how to do this with the XML structure I need to send.

The XML data will look like this:

<Sheet> <Job>jobNumber</Job> <Task>taskNumber</Task> <UserID>3</UserID> <Date>systemDateFormatted</Date> <Minutes>timeToLog</Minutes> <Note>userNote</Note> </Sheet> 

So far I have this for my code.

 try { URL url = new URL(theUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("Sheet", null)); params.add(new BasicNameValuePair("Job", jobNumber)); params.add(new BasicNameValuePair("Task", taskNumber)); params.add(new BasicNameValuePair("UserID", String.valueOf(yourUserID))); params.add(new BasicNameValuePair("Date", systemDateFormatted)); params.add(new BasicNameValuePair("Minutes", timeElapsed)); params.add(new BasicNameValuePair("UserNote", "Test Note")); params.add(new BasicNameValuePair("Sheet", null)); 

I am not sure if I understand NamedValuePair correctly. Would it be better to create a string for my XML data and POST instead?

Thanks!

+3
source share
2 answers

Yes, POST data is transmitted as the payload of your request. for instance

 URL url = new URL(theUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String body = "<xml...</xml>"; OutputStream output = new BufferedOutputStream(conn.getOutputStream()); output.write(body.getBytes()); output.flush(); finally { conn.disconnect(); } 
+1
source

I am not sure if I understand NamedValuePair correctly. Would it be better to create a string for my XML data and POST instead?

Your message seems to be cut off, but from what you show what you are doing, you are not sending XML, but adding request parameters.

Convert the XML to an encoded string, then write it to the output stream that you get from conn.getOutputStream ().

Here is a similar example: fooobar.com/questions/465273 / ...

You would replace the "query" with your XML string.

+1
source

Source: https://habr.com/ru/post/1236098/


All Articles