[英]android : post data to webview
我正在使用Webview發送數據以交換郵件服務器。 (http帖子不適用於帶有大附件的郵件,因此請嘗試此方法)。
請在下面查看我的代碼。
如果我發送的數據完全沒有編碼,則發送失敗。 如果我按照下面的代碼對整個數據進行編碼,那么它仍然會失敗。
如果我嘗試使用注釋的代碼,將數據存儲為名稱值對並對其進行編碼,則會收到郵件,但沒有附件。 那么在這里進行編碼的正確方法是什么? 附件的類型為ContentBody。 所有其他參數均為字符串。
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,);
entity.addPart("hidid", new StringBody(hidid));
entity.addPart("hidchk", new StringBody(hidchk));
entity.addPart("hidcanary", new StringBody(canary));
entity.addPart("attach", attachment);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
entity.writeTo(bytes);
String fullUrl = baseUrl + "?ae=Dialog&t=Attach&a=Add";
webView.postUrl(fullUrl, EncodingUtils.getBytes(bytes.toString(),"BASE64"));
/* List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("hidid", hidid));
parameters.add(new BasicNameValuePair("hidchk", hidchk));
parameters.add(new BasicNameValuePair("hidcanary", canary));
parameters.add(new BasicNameValuePair("attach", attachment.toString()));
UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(parameters);
String fullUrl = baseUrl + "?ae=Dialog&t=Attach&a=Add";
webView.postUrl(fullUrl, EntityUtils.toByteArray(entity1)); */
我看到他的Android WebView :: postUrl方法很難編碼為“ application / x-www-form-urlencoded”。
嘗試將附件轉換為
public static String encodeToBase64(String string)
{
String encodedString = "";
try
{
byte[] byteData = null;
if(Build.VERSION.SDK_INT >= 8) // Build.VERSION_CODES.FROYO --> 8
{
byteData = android.util.Base64.encode(string.getBytes(),android.util.Base64.DEFAULT);
}
else
{
byteData = Base64Utility.encode(string.getBytes(),Base64Utility.DEFAULT);
}
encodedString = new String(byteData);
}
catch (Exception e)
{
}
return encodedString;
}
到base64
bytes.toString()
從您的字節創建一個字符串。 使用toBytesArray()
代替,以獲得一個byte []
然后,EncodingUtils使用一個字符集進行編碼。 BASE64不是字符集。 UTF-8是。 如果您想對字節進行Base64編碼,請使用android.util.Base64.encode(byte[]);
在您的示例中:
webView.postUrl(fullUrl, Base64.encode(bytes.toByteArray(), Base64.DEFAULT));
關於使用MultipartEntity將數據發布到url的博客文章 ,您可能需要在項目中包括一些其他jar文件。 它們包括以下apache開源項目:apache-mime4j,httpclient,httpcore和httpmime。
完成此操作后,您應該可以使用以下代碼作為示例,將字符串和文件都發布到url中:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.tumblr.com/api/write");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(image));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.