我正在尝试实现一个函数,该函数通过 HTTP Post 将 base64 编码图像从 webview 传递到我的 web 应用程序。然后,可以说,这张图片必须立即显示在我的视野中。我使用了这个例子,但它不能正常工作,所以在谷歌搜索了一下之后,我开始使用 AsyncTask:
public void tryUpload(String url, Context context) {
new UploadTask(context).execute(url);
}
private class UploadTask extends AsyncTask<String, Void, HttpResponse> {
private Context context;
public UploadTask(Context ctx) {
context = ctx;
}
@Override
protected HttpResponse doInBackground(String... urls) {
List<NameValuePair> formData = new ArrayList<NameValuePair>(3);
formData.add(new BasicNameValuePair("image", "base64EncodedString"));
HttpPost httpPost = new HttpPost(urls[0]);
try {
httpPost.setEntity(new UrlEncodedFormEntity(formData, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
WebView browser = (WebView) findViewById(R.id.my_web_engine);
browser.setWebChromeClient(new MyWebChromeClient());
browser.setWebViewClient(new MyWebViewClient());
try{
String data = new BasicResponseHandler().handleResponse(response);
browser.loadDataWithBaseURL(urls[0], data, "text/html", HTTP.UTF_8, null);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
if (responseBody.equalsIgnoreCase("OK"))
Log.w("myApp", "Everything is OK");
else
Log.w("myApp", "Something is wrong");
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Intent.ACTION_SEND.equals(action) && type != null) {
if (type.startsWith("image/")) {
// for simplicity skipped image encoding to base64
String url = getResources().getString(R.string.url) + "/MyController/ImageUpload";
Context context = ImageUploadActivity.this;
tryUpload(url, context);
}
}
}
}
这是我的 ASP.NET MVC 操作:
// temporary removed authorization
[HttpPost]
public ActionResult ImageUpload(string image)
{
// skipped some lines
ViewData.Add("imageFromWebView", image);
return View();
}
并且 aView
包含以下行:
<img src="data:image/png;base64,<%: (string)ViewData["imageFromWebView"] %>"/>
当我删除[HttpPost]
时,视图加载没有问题,但图像不显示。
但是当我离开时[HttpPost]
,我得到了一个例外
org.apache.http.client.HttpResponseException: Not Found
在以下行中:
String data = new BasicResponseHandler().handleResponse(response);
有谁知道我做错了什么?