2012-11-19 30 views
4

我想使用webview發出一個http post請求。如何使用webview發佈帖子請求?

webView.setWebViewClient(new WebViewClient(){ 


      public void onPageStarted(WebView view, String url, 
       Bitmap favicon) { 
      super.onPageStarted(view, url, favicon); 
      } 

      public boolean shouldOverrideUrlLoading(WebView view, 
       String url) { 

      webView.postUrl(Base_Url, postData.getBytes()); 

      return true; 
      } 

     }); 

上面的代碼片段加載了網頁。我想訪問這個請求的迴應。

如何使用webview獲取http post請求的響應?

在此先感謝

+0

在這種情況下webView沒有作用,webView只是讓你的網頁顯示在android小工具中,現在它的uoto你在服務器網站上處理你網站上的請求響應,我會建議你使用HTTPPOST調用採取的迴應 –

+0

您的問題是:如何使用Web視圖發佈請求? 比詳細問你問:我如何獲得使用Web視圖的HTTP發佈請求的迴應?那麼你真正的問題是什麼?因此我投了票。 – AndaluZ

回答

5

WebView不允許您訪問HTTP響應的內容。

您必須爲此使用HttpClient,然後通過使用函數loadDataWithBaseUrl並指定基本網址將內容轉發到視圖,以便用戶可以使用webview繼續在網站中導航。

例子:

// Executing POST request 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
httppost.setEntity(postContent); 
HttpResponse response = httpclient.execute(httppost); 

// Get the response content 
String line = ""; 
StringBuilder contentBuilder = new StringBuilder(); 
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
while ((line = rd.readLine()) != null) { 
    contentBuilder.append(line); 
} 
String content = contentBuilder.toString(); 

// Do whatever you want with the content 

// Show the web page 
webView.loadDataWithBaseURL(url, content, "text/html", "UTF-8", null); 
+0

如何使用http post請求與loadDataWithBaseUrl? –

+0

我在答案中增加了一個例子 –

6

首先,HTTP庫的支持添加到您的gradle這個文件: 爲了能夠使用

useLibrary 'org.apache.http.legacy'

這之後您可以使用下面的代碼在你的webview中執行post請求:

public void postUrl (String url, byte[] postData) 
String postData = "submit=1&id=236"; 
webview.postUrl("http://www.belencruzz.com/exampleURL",EncodingUtils.getBytes(postData, "BASE64")); 

http://belencruz.com/2012/12/do-post-request-on-a-webview-in-android/

+2

EncodingUtils已被棄用且無法使用 –

相關問題