6

I have a specific requirement where I have to fire a url on the browser from my activity. I am able to do this with the following code :

String finalUrl = "http://localhost:7001/display/result.jsp?param=12345";
Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse(finalUrl));

Now, I want to invoke result.jsp by passing 'param' as a request header in the request and not as the queryString itself.

Can somebody please advice ?

Thanks a lot in advance

EDIT Even a POST request with the 'param' in the request body should be fine.

EDIT 2 The accepted answer is for the POST request, not for the headers.

Vinay
  • 405
  • 2
  • 10
  • 17

1 Answers1

14

The Android Browser support 'viewing' javascript, for example the following code can launch the Browser app to show an alert dialog:

    String finalUrl = "javascript:alert('hello')";
    Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW,
                            Uri.parse(finalUrl));
    startActivity(browserIntent);

A common trick to do post operation by javascript is that you create a form by javascript and then submit it. So in theory code like below should work (part of the code is copied from this post):

    //String finalUrl = "http://localhost:7001/display/result.jsp?param=12345";
    String finalUrl = "javascript:" + 
        "var to = 'http://localhost:7001/display/result.jsp';" +
        "var p = {param:'12345',param2:'blablabla',param3:'whatever'};"+
        "var myForm = document.createElement('form');" +
        "myForm.method='post' ;" +
        "myForm.action = to;" +
        "for (var k in p) {" +
            "var myInput = document.createElement('input') ;" +
            "myInput.setAttribute('type', 'text');" +
            "myInput.setAttribute('name', k) ;" +
            "myInput.setAttribute('value', p[k]);" +
            "myForm.appendChild(myInput) ;" +
        "}" +
        "document.body.appendChild(myForm) ;" +
        "myForm.submit() ;" +
        "document.body.removeChild(myForm) ;";
    Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW,
                            Uri.parse(finalUrl));
    startActivity(browserIntent);
Ziteng Chen
  • 1,959
  • 13
  • 13
  • Works absolutely fine... Thanks a ton Mr. Ziteng... Saved me a lot of time and stress :) – Vinay Oct 15 '12 at 09:25