【问题标题】:How do I submit variables from Android Activity to website url?如何将变量从 Android Activity 提交到网站 url?
【发布时间】:2025-12-21 05:15:12
【问题描述】:

我构建了一个像表单一样工作的应用程序,它需要四个字段并验证信息以确保没有输入无效字符。这四个字段存储在变量中:

  • 电话
  • 姓名
  • 电子邮件
  • 评论

    现在我想将表单数据(在这四个字段中输入并存储到变量中的任何内容)提交到一个 url(将使用http://www.test.com),但我不知道如何去做。我想我正在寻找一种叫做 HttpURLConnection 的东西,但我不确定如何指定发送哪个变量。下面的代码是我从网站http://developer.android.com/reference/java/net/HttpURLConnection.html找到的

    private class UploadFilesTask extends AsyncTask<URL, Integer, Long>{
    protected Long doInBackground(URL... urls) {
    
        try {
            HttpClient http = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.test.com");
    
            List<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new BasicNameValuePair("phone", "value"));
            data.add(new BasicNameValuePair("name", "value"));
            data.add(new BasicNameValuePair("email", "value"));
            data.add(new BasicNameValuePair("comments", "value"));
            post.setEntity(new UrlEncodedFormEntity(data));
    
            HttpResponse response = http.execute(post);
            // do something with the response
        }
        catch (ClientProtocolException e) {
            // do something
            finish();
        }
        catch (IOException e) {
            // do something
            finish();
        }
    

    }

    }

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 网站是否接受参数值对中的值,我的意思是在 URL 重写中?
  • 服务器期望什么? POST 请求?在查询字符串中带有参数的 GET 请求?
  • 我相信服务器需要一个 POST 请求

标签: java android http-post httpurlconnection


【解决方案1】:

将表单数据发送到服务器的最简单方法是使用 HttpClient 和 HttpPost。

试试这样的:

try {
    HttpClient http = new DefaultHttpClient();
    HttpPost   post = new HttpPost("http://www.example.com/process");

    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new BasicNameValuePair("phone", "value");
    data.add(new BasicNameValuePair("name", "value");
    data.add(new BasicNameValuePair("email", "value");
    data.add(new BasicNameValuePair("comments", "value");
    post.setEntity(new UrlEncodedFormEntity(data));

    HttpResponse response = http.execute(post);
    // do something with the response
}
catch (ClientProtocolException e) {
    // do something
}
catch (IOException e) {
    // do something
}

请注意,您需要在 AsyncTask 中执行此操作,这样您就不会锁定等待网络操作完成的 UI 线程。

编辑

这是一个简单的快速示例,说明它在 AsyncTask 中的外观。

public class SendTask extends AsyncTask<Void, Void, Boolean> {

    String responseString;

    @Override
    protected Boolean doInBackground(Void... params) {
        try {

            HttpClient http = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.test.com");

            List<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new BasicNameValuePair("phone", "value"));
            data.add(new BasicNameValuePair("name", "value"));
            data.add(new BasicNameValuePair("email", "value"));
            data.add(new BasicNameValuePair("comments", "value"));
            post.setEntity(new UrlEncodedFormEntity(data));

            HttpResponse response = http.execute(post);
            responseString = new BasicResponseHandler().
                                 handleResponse(response); // Basic handler
            return true;
        }
        catch (ClientProtocolException e) {
            // do something useful to recover from the exception
            // Note: there may not be anything useful to do here
        }
        catch (IOException e) {
            // do something useful to recover from the exception
            // Note: there may not be anything useful to do here
        }           
        return false;
    }
    @Override
    protected void onPostExecute(Boolean success) {
        // TODO: Do something more useful here
        if (success) {
            Toast.makeText(MainActivity.this, "Success: " + responseString, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
        }
    }
}

【讨论】:

  • 不错,简单的例子。虽然应该提到,您通常应该使用 ResponseHandler 来处理 HTTP 响应——这可以确保始终使用实体并正确释放连接。
  • @nEx.Software 谢谢你的例子,这肯定会解决一些问题。但是我确实有一些问题,这两个catch 语句是做什么的,以及如何在AsyncTask 中执行这个操作?我只是在使用它的类上扩展 AsyncTask 吗?
  • 两个 catch 语句是必需的,因为 HttpClient.execute(...) 可以抛出这些异常。我怀疑您是否曾经遇到过 ClientProtocolException,但如果无法建立连接,您可能会遇到 IOException。就使用 AsyncTask 而言,创建一个扩展 AsyncTask 的内部类(甚至是匿名类)并在 doInBackground 方法中使用上述方法。
  • @nEx.Software 我更新了上面的代码,但我认为我还没有。你能帮我解决你认为上面的代码有什么问题吗?谢谢
  • 嗯,这取决于。我在技术上唯一认为新代码“错误”的是 catch 中的 finish() 调用。如果您不发送任何参数、更新进度或返回任何结果,您也可以将其更改为 extends AsyncTask&lt;Void, Void, Void&gt; {。我已经添加了一个示例,说明您可以如何处理它。
【解决方案2】:

将字段作为参数添加到 url。

String phone="phone=234432";
String name="name=John Smith";
String email="email=test@email.com"; 

Url = new URL("http://www.test.com?"+phone+"&"+name+"&"+email);

未经测试,但它应该可以在 GET Http 请求中工作。

【讨论】:

  • 我有点迷茫,这怎么把数据发送到指定的url?
【解决方案3】:

//使用xml请求

String url="http://www.test.com";
String xmlRequest="<message xmlns=\"http://test.com/schemas/ma\"><header></header>"+
"<body><phone>9944556622</phone><name>Mytest name</name><email>mytest@email.com</email>"+"<comments>hay this seems nice</comments></body></message>"

HttpPost httppost = new HttpPost(url);
    StringEntity se = new StringEntity(xmlRequest,HTTP.UTF_8);


httppost.setHeader("Content-Type","application/xml");
httppost.setHeader("Accept","application/xml");

httppost.setEntity(se);

BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);

   StatusLine statusLine = httpResponse.getStatusLine();

【讨论】:

  • 感谢您的回复。你能走过来向我解释你在做什么吗?我可以用变量替换xml中的静态文本吗?
  • 实际上你需要api参考,即如何发送请求并从你的服务器获取响应。
  • 如果你有 api 你需要先在 REST Client 中尝试。如果它直接成功,您可以在您的程序中执行此操作。
【解决方案4】:
    HttpClient httpClient = new DefaultHttpClient();
                    Log.i("sampath","line 139");
                    HttpPost httpPost = new HttpPost(url);

                    BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("textMessage", msg);

                    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                    nameValuePairList.add(usernameBasicNameValuePair);

                    try {

                        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);


                        httpPost.setEntity(urlEncodedFormEntity);

                        try {

                            HttpResponse httpResponse = httpClient.execute(httpPost);


                            InputStream inputStream = httpResponse.getEntity().getContent();

                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                            StringBuilder stringBuilder = new StringBuilder();

                            String bufferedStrChunk = null;

                            while((bufferedStrChunk = bufferedReader.readLine()) != null){
                                stringBuilder.append(bufferedStrChunk);
                            }

                            return stringBuilder.toString();

                        } catch (ClientProtocolException cpe) {
                            System.out.println("Firstption caz of HttpResponese :" + cpe);
                            cpe.printStackTrace();
                        } catch (IOException ioe) {
                            System.out.println("Secondption caz of HttpResponse :" + ioe);
                            ioe.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException uee) {
                        System.out.println("Anption given because of UrlEncodedFormEntity argument :" + uee);
                        uee.printStackTrace();
                    }

//---------------------------------------------------------------------------
Here is the php file

<?php
$message = $_POST['textMessage'];
echo 'working fine'.$message;
$filename="androidmessages.html";
file_put_contents($filename,"Entered Text is:".$message."<br />",FILE_APPEND);
?>

【讨论】:

  • 确保在 php 文件所在的同一目录中创建 androidmessages.html