我想在android中使用httpurlconnection将一些参数发布到服务器,我的数据是嵌套的JsonObject,我必须先对其进行编码,但这是错误的,因为我从服务器收到状态错误,这是我的编码函数和Jsonobject:
private static String encodeParams(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
我的嵌套json:
JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "Manjeet");
postDataParams.put("email", "manjeet@gmail.com");
JSONObject par = new JSONObject();
par.put("class", "a");
par.put("family", "aray");
postDataParams.put("par", par);
答案 0 :(得分:1)
从输出构造一个URI,仅对字符?#/
进行编码
比循环容易得多
您可以使用URI,它会产生不同的输出和结果 以下示例
new URI("http", "host.com", "/path/", "key=| ?/#ä", "fragment").toURL();
产生结果http://host.com/path/?key=%7C%20?/%23ä#fragment。请注意如何将诸如?&/之类的字符编码为不允许URI查询字符串 (从API复制)
答案 1 :(得分:1)
我不确定这段代码,因为我从未使用过JSONObject,但是我将尝试向您展示想法:
创建一个返回对象所有属性(包括嵌套属性)的方法:
Map<String, String> jobjectToMap(JSONObject jo) {
Map<String, String> properties = new HashMap<String, String>;
Iterator<String> itr = jo.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = jo.optJSONObject(key);//this will returns null if the value is not a JSONObject from https://docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html#getJSONObject-java.lang.String-
if(value != null) { //nested object
properties.putAll(jobjectToMap(value));
} else {
properties.put(key, jo.get(key)); //primitive one
}
}
return properties;
}
创建另一个将地图转换为网址的方法
public String queryParams(Map<String, String> params)
throws UnsupportedEncodingException
{
StringBuilder queryString = new StringBuilder();
if (params.size() > 0) {
queryString.append('&');
}
// Convert the params map into a query string.
for (Map.Entry<String, String> entry : params.entrySet())
{
String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
String encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8");
queryString.append(encodedKey);
queryString.append('=');
queryString.append(encodedValue);
}
return queryString.toString();
}