Submit form with POST data in Android app

2019-03-11 18:34发布

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.

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.

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.

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-03-11 19:19

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 (NOTE Also contains waiting implementation to return a response, probably not every day implementation of network call):

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;
    } 
}
查看更多
何必那么认真
3楼-- · 2019-03-11 19:37

What's wrong with them just using the built in browser? You can also submit a form using UrlEncodedFormEntity and 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.

查看更多
登录 后发表回答