如何在JSON
中发送WebView
发布数据以调用包含原始数据的网络服务?
这是我的代码,
fb.loadData(base64, "text/html; charset=UTF-8", "base64");
答案 0 :(得分:1)
尝试
webView.postUrl("url", data.getBytes("UTF-8"));
答案 1 :(得分:1)
假设这是你的json: 1.
ReqBody : [{
'LoginId':'LoginId',
'pass' :'pass'
}
]
你的pojo课程将是:
public class ExamplePojo{
@SerializedName("LoginId")
private String LoginId;
@SerializedName("pass")
private String Password;
//getter setter method
}
2.使用Gson将指定对象序列化为等效的Json表示。
public static String getJsonString(Object obj) throws JSONException {
Gson gson = new Gson();
if (obj != null) {
String json = gson.toJson(obj);
JSONObject jsonObject = new JSONObject(json);
return jsonObject.toString();
} else
return "";
}
3.Post this data(Return by getJsonString() say dataToPost ) as per your requirement
4.假设您必须在键值对中发送数据,然后添加以下内容:
NameValuePair dataToSend = new NameValuePair("key", dataToPost);
postData = getQuery(dataToSend);
private String getQuery(NameValuePair params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
result.append(URLEncoder.encode(params.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(params.getValue(), "UTF-8"));
// }
return result.toString();
}
try {
mWebView.postUrl(URL, postData.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
OR
URL url;
String response = "";
try {
url = new URL(URL);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod("POST");
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(dataToSend);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
响应将是html页面,您可以在webview上发布如下: mWebView.loadData(response,“text / html”,“utf-8”);
答案 2 :(得分:0)
如果你想将jsonObject数据作为api body传递给webview,你可以试试这个->
HashMap
String postdata1 = "";
int i = 1;
for (Map.Entry
webView.postUrl(url, postdata1 .getBytes());
或
直接使用这样的键值
"KEY1="+ URLEncoder.encode(postData.getAmount().toString(), "UTF-8")+
"&KEY2="+URLEncoder.encode(postData.getBackref(), "UTF-8") +
"&KEY3="+URLEncoder.encode(postData.getCountry(), "UTF-8") +