Android WebView Post Request with Custom Headers

后端 未结 2 583
攒了一身酷
攒了一身酷 2021-02-19 05:36

I could see there are two separate methods in Android docs to post the data and add the headers.

For setting Headers
public void loadUrl (String url, Map

        
2条回答
  •  情书的邮戳
    2021-02-19 05:52

    I've bumped on same problem recently and after couple of hours solved it.

    Here is my code snippet with some comments:

    HttpClient httpclient = new DefaultHttpClient();
    
    HttpPost httpPost = new HttpPost(getPostUrl());
    
    // example of adding extra header "Referer"
    httpPost.addHeader("Referer", getReferer()); 
    
    ArrayList postParameters = new ArrayList();
    
    for (PostItem postItem : getPostItems()) { 
        // key value post pairs
        // add post parameters in array list
        postParameters.add(new BasicNameValuePair(postItem.getKey(), postItem.getValue())); 
    }
    
    HttpResponse response = null;
    
    try {
        mWebView.getSettings().setJavaScriptEnabled(true);
        httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
    
        response = httpclient.execute(httpPost);
    
        BasicResponseHandler responseHandler = new BasicResponseHandler();
        String htmlString = responseHandler.handleResponse(response);
    
        // important!! is to fill base url
        mWebView.loadDataWithBaseURL(getPostUrl(), htmlString, "text/html", "utf-8", null); 
    
    } catch (Exception e){
        // handle errors
    }
    

提交回复
热议问题