在 Android 应用程序中提交带有 POST 数据的表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2999945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:13:49  来源:igfitidea点击:

Submit form with POST data in Android app

androidformspostandroid-intent

提问by datguywhowanders

I've been searching the web for a way to do this for about a week now, and I just can't seem to figure it out.

我已经在网上搜索了大约一个星期的方法来做到这一点,但我似乎无法弄清楚。

I'm trying to implement an app that my college can use to allow users to log in to various services on the campus with ease. The way it works currently is they go to an online portal, select which service they want, fill in their user name and pwd, and click login. The form data is sent via post (it includes several hidden values as well as just the user name and pwd) to the corresponding login script which then signs them in and loads the service.

我正在尝试实施一个应用程序,我的大学可以使用该应用程序让用户轻松登录校园内的各种服务。目前的工作方式是他们进入一个在线门户,选择他们想要的服务,填写他们的用户名和密码,然后点击登录。表单数据通过 post(它包括几个隐藏值以及用户名和密码)发送到相应的登录脚本,然后登录脚本并加载服务。

I've been trying to come at the problem in two ways. I first tried a WebView, but it doesn't seem to want to support all of the html that normally makes this form work. I get all of the elements I need, fields for user and pwd as well as a login button, but clicking the button doesn't do anything. I wondered if I needed to add an onclick handler for it, but I can't see how as the button is implemented in the html of the webview not using a separate android element.

我一直试图以两种方式解决这个问题。我首先尝试了 WebView,但它似乎不想支持通常使此表单工作的所有 html。我得到了我需要的所有元素,用户和密码字段以及登录按钮,但单击该按钮没有任何作用。我想知道是否需要为它添加一个 onclick 处理程序,但我看不到按钮是如何在 webview 的 html 中实现的,而不是使用单独的 android 元素。

The other possibility was using the xml widgets to create the form in a nice relative layout, which seems to load faster and looks better on the android screen. I used EditText fields for the input, a spinner widget for the service select, and the button widget for the login. I know how to make the onclick and item select handlers for the button and spinner, respectively, but I can't figure out how to send that data via POST in an intent that would then launch a browser. I can do an intent with the action url, but can't get the POST data to feed into it.

另一种可能性是使用 xml 小部件在一个很好的相对布局中创建表单,这似乎加载速度更快并且在 android 屏幕上看起来更好。我使用了 EditText 字段作为输入,使用了一个用于服务选择的微调小部件,以及用于登录的按钮小部件。我知道如何分别为按钮和微调器制作 onclick 和 item select 处理程序,但我无法弄清楚如何通过 POST 在随后启动浏览器的意图中发送该数据。我可以使用操作 url 执行意图,但无法将 POST 数据输入其中。

So here is what I have right now...

所以这就是我现在所拥有的......

HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(action);
String endResult = null;

try 
{
post.setEntity(new UrlEncodedFormEntity(myList));
} 
catch (UnsupportedEncodingException e) 
{
// TODO Auto-generated catch block
e.printStackTrace();
} 

try 
{
String response = client.execute(post, new BasicResponseHandler());
endResult = response;
} 
catch (ClientProtocolException e) 
{
// TODO Auto-generated catch block
e.printStackTrace();
} 
catch (IOException e) 
{
// TODO Auto-generated catch block
e.printStackTrace();
}  

So my question now... is how do I take the endResult screen, which should be the page returned after I logged in to my service, and display it in a browser?

所以我现在的问题是......我如何获取 endResult 屏幕,它应该是我登录到我的服务后返回的页面,并在浏览器中显示它?

采纳答案by Robby Pond

What's wrong with them just using the built in browser? You can also submit a form using UrlEncodedFormEntityand HttpClient.

他们只使用内置浏览器有什么问题?您还可以使用UrlEncodedFormEntity和 HttpClient提交表单。

HttpParams params = new DefaultHttpParams(); // setup whatever params you what
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost("someurl");
post.setEntity(new UrlEncodedFormEntity()); // with list of key-value pairs
client.execute(post, new ResponseHandler(){}); // implement ResponseHandler to handle response correctly.

Okay and after you have the response in a string. The response since its a page is going to be in html. You need to use a WebView to show the html. WebView has a method loadData() that takes a string of html and displays it.

好的,在你得到一个字符串的响应之后。因为它的一个页面的响应将在 html 中。您需要使用 WebView 来显示 html。WebView 有一个方法 loadData() 接受一串 html 并显示它。

回答by Graeme

Based on @RobbyPonds answer, for the benefit of people wandering past here, below is a generic implementation to post and receive a response from a URI (NOTEAlso contains waiting implementation to return a response, probably not every day implementation of network call):

基于@RobbyPonds 的回答,为了让路过这里的人们受益,下面是一个从 URI 发布和接收响应的通用实现(注意还包含等待实现以返回响应,可能不是网络调用的日常实现):

private static String responseValue;

@SuppressWarnings({ "unchecked", "rawtypes" })  
public static String sendPostToTargetAndWaitForResponse() throws ClientProtocolException, IOException {     
    final Thread currentThread = Thread.currentThread();
    synchronized (currentThread) {      

        HttpParams params = new BasicHttpParams();
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(HTTP_POST_URI);

        // List Creation with post data for UrlEncodedFormEntity
        ArrayList<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new NameValuePair() {

            @Override
            public String getValue() {
                return getSampleJSON();
            }

            @Override
            public String getName() {
                return "json";
            }
        });
        post.setEntity(new UrlEncodedFormEntity(mList)); // with list of key-value pairs
        client.execute(post, new ResponseHandler(){

            @Override
            public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
                synchronized (currentThread) {                          
                    currentThread.notify();
                }
                return null;
            }
        }); 
        try {
            currentThread.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return responseValue;
    } 
}