简体   繁体   English

android使用HttpURLConnection请求一个php web服务并提交php表单

[英]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 我想用我的android应用程序解析一个php web服务,我创建了一个这样的url连接

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. getInputStream之后,我使用pull解析器来解析xml数据,但我的问题是Web服务需要提交表单来获取xml数据。 How can I click this button from my java code? 如何从我的java代码中单击此按钮? Is this possible or do I need to change the web service ? 这是可能的还是我需要更改Web服务?

Follow these steps if you want to read data from webservide: In your button's onclick listener 如果要从webservide读取数据,请执行以下步骤:在按钮的onclick监听器中

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

in asynctask's doInBackground method: 在asynctask的doInBackground方法中:

   @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: 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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