【发布时间】:2012-04-05 07:43:01
【问题描述】:
尝试从 Android 在服务器上发布 json 时遇到问题。错误是:
加载 JSON 失败。特殊字符不能包含在 要求。请检查请求的 JSON。
我遵循了许多示例,但没有一个有用。请提出解决方案或帮我找出代码中的问题。
以下是在服务器上发布 JSON 字符串的代码。
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
/* ====================================================================================================*/
JSONObject listobj = new JSONObject ();
JSONObject listInvoice = new JSONObject ();
listInvoice.put("client_id","");
listInvoice.put("date_from","");
listInvoice.put("date_to","");
listInvoice.put("invoice_number","");
listInvoice.put("invoice_record_status","");
listInvoice.put("invoice_status","");
listInvoice.put("page","1");
listInvoice.put("per_page_record","10");
listobj.put("listInvoice", listInvoice);
//--List nameValuePairs = new ArrayList(1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json_data", listobj.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("JSON",listobj.toString());
/*======================================================================================================*/
HttpResponse httpResponse = httpClient.execute(httpPost);
String is = EntityUtils.toString(httpResponse.getEntity());
Log.d("JSON","RESPONSE : " + is);
//--HttpEntity httpEntity = httpResponse.getEntity();
//--is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
Log.e("JSON",e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
【问题讨论】:
-
[Json 中的特殊字符可能会出现暂停问题][1]。尝试使用小写特殊字符免费键。 [1]:stackoverflow.com/questions/7866063/…
-
为什么使用 iso-8859-1 编码?为什么不是 utf-8?
-
@kknot 我也检查了 utf-8,但仍然面临同样的问题
-
@ManojPal 是的,我没有说这会帮助你解决这个问题,但会帮助你解决这个问题 :)