简体   繁体   中英

android request a php web service using HttpURLConnection and submit the php form

I want to parse a php web service using my android application, I create a connection to the url like this

InputStream stream = null ;
URL url = new URL(url);
HttpURLConnection conn;
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(30000);
stream =conn.getInputStream();

after getInputStream , I am using pull parser to parse xml data, but my problem is the web service requires to submit the form to get xml data. How can I click this button from my java code? Is this possible or do I need to change the web service ?

Follow these steps if you want to read data from webservide: In your button's onclick listener

new urlConTask().execute() //use asynctask

in asynctask's doInBackground method:

   @Override
        protected String doInBackground(String... params) {

            String url = ur url here;
            String response = "";
            try {
                 response = HttpConnect.sendGet(url);//sendGet is method defined in HttpConnect.java. Its a custom class

            } catch (Exception e) {
                e.printStackTrace();
            }

sendGetMethod:

   public static String  sendGet(String url) throws Exception {



        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

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

        //print result
        return response.toString(); //this is your response

    }

Your app will not be abled to "click" submit button. You said that the submit button submit all the form. Your app should do the request triggered by the submit button.

我必须更改Web服务并使其获得GET和POST,然后我必须放入我的代码

conn.setRequestMethod("GET");

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