• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Post XML Code not working

JonasJWW

Newbie
Hey there,

I need to post XML Code to the URL: http://www.http.com//(MyIP)/data/changes.xml. I tried a lot some codes I found in tutorals but nothing works. I have this reight now but I always get the Error1 and Error2. Does anyone knows what im doing wrong? I apprechiate every help, thanks!

Code:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        httpPostRequest(constructXml());
    }

    public void onUpdate(View view) {
        fewMyXML getMyXML = new fewMyXML();
        getMyXML.execute();
        temp = getMyXML.actual();


        // Binding data
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, temp);
        list.setAdapter(adapter);
    }

    public static void httpPostRequest(String data) {
        BufferedReader reader = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://www.http.com//(MyIP)/data/changes.xml");

            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());


            wr.write(data);
            wr.flush();

            Log.d("post response code", conn.getResponseCode() + " ");

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Error1", "error1");
        } finally {
            try {
                reader.close();
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
                Log.d("Error2", "error2");
            }
        }
        Log.d("Error3", "Error3");
    }

    public String constructXml(){
        //DATA
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Devices> <Device> <ID>EZR010A49</ID> <HEATAREA nr=\"4\"> <T_TARGET>19</T_TARGET> </HEATAREA> </Device> </Devices>");

        return sb.toString();
    }
 
Hi. To start with, we need more information about the errors. There are a number of problems with your code

First, do not catch "Exception". This is generally bad practice because Exception is very general. You should catch more specific types of Exception.

Secondly, your log statements throw away all the useful information in the Exception. Like what the Exception is. We need this to help diagnose the problem.

Start by taking out the Exception class from your catch blocks, and only catch checked Exceptions. In Java there are two main types of Exception - checked and unchecked. The former is enforced by the compiler, and must be added to your code in a catch block. The latter doesn't have to be caught explicitly by code, and may happen at runtime. These types of Exception are caught by the system, and will terminate your app.
By catching Exception explicitly, you're catching ALL possible Exceptions that may occur (checked and unchecked). But like I say, the way your code is written, you're throwing away all the information about what type of Exception has been thrown.

As it stands, you have two options:-

1. Take out the catch blocks and let the system catch and report the Exceptions. This will give a complete stack trace
2. Report the information contained in the Exception within your catch block. Do this by using the log statement like this

Code:
log.d(e.toString())
 
HI LV426, first of all thank you very much for the hepl!

I couldn´t take out the catch blocks but I print the Exceptions out on the Console. I updated the Code to this:
Code:
public static void httpPostRequest(String data) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://www.http.com//192.168.178.38/data/changes.xml");           
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write(data);
            wr.flush();

            Log.d("post response code", conn.getResponseCode() + " ");

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Error1", e.toString());
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
                Log.d("Error2", ex.toString());
            }
        }
    }

I removed the BufferedReader, I didnt used it, so the error2 was because it was a null object.
Now to Error1, the Console puts out: Error1: android.os.NetworkOnMainThreadException, As far as I know, I need to let the class extend from AsyncTask. But im not sure how i do it and if it would fix my problem
 
Yes you need to use AsyncTask. There are many examples on the web explaining how to do this.
 
Ok so I made this AsyncTask now:
Code:
public class poster extends AsyncTask {
    @Override
    protected Object doInBackground(Object[] objects) {

        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://www.http.com//192.168.178.38/data/changes.xml");

            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write(constructXml());
            wr.flush();
            Log.d("POSTED", "POSTED");
            Log.d("post response code!", conn.getResponseCode());

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Error1", e.toString());
        } finally {
            try {
                //reader.close();
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
                Log.d("Error2", ex.toString());
            }
        }
        return new String("");
    }

    public static String constructXml(){
        //DATA
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Devices> <Device> <ID>EZR010A49</ID> <HEATAREA nr=\"4\"> <T_TARGET>19</T_TARGET> </HEATAREA> </Device> </Devices>");

        return sb.toString();
    }

}

And I have this in onCreate in my MainActivity:
Code:
poster post = new poster();
        post.execute();
        Log.d("Posting", "posting");

Now there are no errors but it still doesnt work. I dont know its its a problem with my code or with the XML Interface. It says this in the Console but I dont really know what it means:

12-20 20:19:43.970 4643-4643/com.example.jonas.heizung1 D/Posting: posting
12-20 20:19:43.987 4643-4666/com.example.jonas.heizung1 D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

[ 12-20 20:19:43.989 4643: 4643 D/ ]
HostConnection::get() New Host Connection established 0xb4390dd0, tid 4643


[ 12-20 20:19:43.989 4643: 4643 W/ ]
Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1
12-20 20:19:43.990 4643-4643/com.example.jonas.heizung1 D/Atlas: Validating map...
12-20 20:19:44.027 4643-4666/com.example.jonas.heizung1 I/OpenGLRenderer: Initialized EGL, version 1.4
12-20 20:19:44.028 4643-4666/com.example.jonas.heizung1 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
12-20 20:19:44.039 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglCreateContext: 0xb4369a60: maj 2 min 0 rcv 2
12-20 20:19:44.042 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:44.044 4643-4666/com.example.jonas.heizung1 D/OpenGLRenderer: Enabling debug mode 0
12-20 20:19:44.061 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:44.122 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:44.151 4643-4643/com.example.jonas.heizung1 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
12-20 20:19:44.159 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:44.223 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:44.243 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:44.282 4643-4667/com.example.jonas.heizung1 D/POSTED: POSTED
12-20 20:19:45.973 4643-4666/com.example.jonas.heizung1 D/EGL_emulation: eglMakeCurrent: 0xb4369a60: ver 2 0
12-20 20:19:46.022 4643-4667/com.example.jonas.heizung1 W/System.err: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
12-20 20:19:46.022 4643-4667/com.example.jonas.heizung1 W/System.err: at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:592)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at libcore.io.IoBridge.recvfrom(IoBridge.java:556)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at java.net.PlainSocketImpl.read(PlainSocketImpl.java:485)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okio_Okio$2.read(Okio.java:113)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okio.RealBufferedSource.indexOf(RealBufferedSource.java:147)
12-20 20:19:46.023 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:94)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:179)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:628)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:388)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:500)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at com.example.jonas.heizung1.poster.doInBackground(poster.java:41)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at java.lang.Thread.run(Thread.java:818)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: Caused by: android.system.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at libcore.io.Posix.recvfromBytes(Native Method)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at libcore.io.Posix.recvfrom(Posix.java:185)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:250)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: at libcore.io.IoBridge.recvfrom(IoBridge.java:553)
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 W/System.err: ... 19 more
12-20 20:19:46.024 4643-4667/com.example.jonas.heizung1 D/Error1: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
 
from the top I see

12-20 20:19:43.987 4643-4666/com.example.jonas.heizung1 D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

then I see the first exception is


[ 12-20 20:19:43.989 4643: 4643 W/ ]
Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1


It looks to me like your telling Gl renderer to do something that's not supported by the version of GLES your running in your emulator.

I'd recommend investigating unmet dependencies or incompatible API's

then there's this

12-20 20:19:44.027 4643-4666/com.example.jonas.heizung1 I/OpenGLRenderer: Initialized EGL, version 1.4
12-20 20:19:44.028 4643-4666/com.example.jonas.heizung1 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without..

and further down this

12-20 20:19:46.022 4643-4667/com.example.jonas.heizung1 W/System.err: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)

and after that it ALL went bad because the emulator dropped the socket and reset the connection.

I bet your problem is in the version of openGL renderer your using on the emulator...

Just my two cents.

Astr4y4L
Team_Astr4y4L
 
Thank you guys for your help, I really apprechiate it but I dont really know anything about this "server/connection topic". My initial plan was to create a little app to control our heating system with this xmp api (https://www.moehlenhoff.de/images/content/oem/Alpha2_XML_Schnittstellen_Informationen.zip). In this document it says: "The XML command is sent to the URL: http://<IP>/data/changes.xml via http post". So since this is not working do you recommed me to contact the manufacturer?
 
Thank you guys for your help, I really apprechiate it but I dont really know anything about this "server/connection topic". My initial plan was to create a little app to control our heating system with this xmp api (https://www.moehlenhoff.de/images/content/oem/Alpha2_XML_Schnittstellen_Informationen.zip). In this document it says: "The XML command is sent to the URL: http://<IP>/data/changes.xml via http post". So since this is not working do you recommed me to contact the manufacturer?

Have you tried sending the command manually via command line?
I'd try that first.
not quite sure on the command or syntax but I'm sure you could find something simmilar and tweak it to fit...

if the device your sending the command to is running some sort of http daemon you may need to check permissions on the back end...

really though I'm not sure.

Astr4y4L
 
Back
Top Bottom