WebViewにてステータスコードを取得できない。 AndroidStudioにてWebViewを使ったアプリを制作しています。タイトル通りWebViewにてステータスコードを取得している参考サイトは見つかったのですが、取得しているステータスコードをTextViewに表示する事ができません。 どうすれば表示できるでしょうか? ご指摘願いたいです。お願い致します。 目的 ・ステータスコード(404や500などの数字)をTextViewに表示したい。 参考url http://saki0n.blogspot.jp/2013/04/android-webview.html 以下ソースコード ------ ーー ーーー import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.ByteArrayInputStream; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView myWebView = (WebView) findViewById(R.id.webView); textView = (TextView) findViewById(R.id.textView); //myWebView.setWebViewClient(new WebViewClient()); myWebView.setWebViewClient(new WebViewClient() { @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (!url.matches("https?://[\\w\\.\\-]+(/.*)?")) { return super.shouldInterceptRequest(view, url); } HttpGet req = new HttpGet(url); DefaultHttpClient client = new DefaultHttpClient(); String mimeType = null, encoding = null; byte[] data = null; try { HttpResponse res = client.execute(req); // ここでステータスコードを取得できるよ! if (HttpStatus.SC_OK == res.getStatusLine().getStatusCode()) { HttpEntity entity = res.getEntity(); Header mimeHeader = entity.getContentType(); textView.setText(res.getStatusLine().getStatusCode()); if (null != mimeHeader) mimeType = mimeHeader.getValue(); Header encodingHeader = entity.getContentEncoding(); if (null != encodingHeader) encoding = encodingHeader.getValue(); data = EntityUtils.toByteArray(entity); } } catch (Exception e) { String msg = e.getMessage(); Log.e(this.getClass().getSimpleName(), (null != msg) ? msg : ""); } finally { req.abort(); client.getConnectionManager().shutdown(); } InputStream stream = new ByteArrayInputStream(data); return new WebResourceResponse(mimeType, encoding, stream); } }); myWebView.loadUrl("https://www.google.com/"); } } ーーー お願い致します。
↧