【发布时间】:2016-09-19 08:42:29
【问题描述】:
我如何在WebView 中发送JSON 发布数据以使用原始数据调用网络服务?
这是我的代码,
fb.loadData(base64, "text/html; charset=UTF-8", "base64");
【问题讨论】:
-
使用WebView调用webservice有什么意义?
标签: java android android-studio
我如何在WebView 中发送JSON 发布数据以使用原始数据调用网络服务?
这是我的代码,
fb.loadData(base64, "text/html; charset=UTF-8", "base64");
【问题讨论】:
标签: java android android-studio
假设这是你的 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");
【讨论】:
试试
webView.postUrl("url", data.getBytes("UTF-8"));
【讨论】:
如果你想将jsonObject数据作为api body传递给webview,你可以试试这个->
HashMap
字符串 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") +
【讨论】: