【问题标题】:HTTP post Doesn't Work in my android appHTTP post 在我的 android 应用程序中不起作用
【发布时间】:2015-02-13 13:57:14
【问题描述】:
String HttpPost(String aURL) throws Exception
    {
        URL url = new URL(aURL);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String response="";
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            response+=inputLine;    

      //  Log.i(TAG, response);
        if(in!=null)
         in.close();
        return response;
   }


public void userpost(View v){

        txtUsername = (EditText) findViewById(R.id.txtUserName);
        txtUserphone = (EditText) findViewById(R.id.txtUserphone);
        txtUserphone = (EditText) findViewById(R.id.txtUsermail);

        String Username = txtUsername.getText().toString();
        String Userphone = txtUserphone.getText().toString();
        String Usermail = txtUserphone.getText().toString();

        //action=staffadd&&sname=test1&&mobile=78545656566&&email=abr@abr.com&&imei=78945641235645
        String conString = "";
        conString = "action=staffadd";
        conString = url + "?" + conString +"&&sname=" +Username +"&&mobile=" +Userphone +"&&email=" + Usermail +"&&imei="+iIMEI;

        try {
            String response =HttpPost(conString);

            Log.i("REQUEST", conString);
            Log.i("Response", response);

            if (response.startsWith("Y")){

                return;
            }

            else if(response.startsWith("N"))
                return;

        } catch (Exception e) {

        }   

    }

如果我点击提交按钮,我得到了

02-13 00:13:02.103:I/Choreographer(553):跳过 53 帧!这 应用程序可能在其主线程上做了太多工作。

我在 android 4.4 中开发此应用

【问题讨论】:

标签: android android-activity


【解决方案1】:

问题是您在 UI 或主线程中使用 Web 服务,因此您需要将 AsyncTask 用于 Web 服务。 请参阅此link。这给出了如何使用 AsyncTask 的想法。 这是最常见的错误

那个链接提到了你的一切。我只是在这里添加代码。

第 1 步: 首先你需要像这样调用Asynctask

new DownloadFilesTask().execute(url1, url2, url3);

第 2 步: 实现你的 Async 类

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

注意:有onPreExecute()doInBackground()onPostExecute()三种方法。在doInBackground() 方法下做你的下载工作。

这只是示例代码。试试你自己的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2019-09-22
    • 2018-06-04
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多