我试图通过android发送一个JSON字符串,而iam试图通过http://www.jsontest.com/#validate验证它。
我收到回复:
“error”:“JSONObject文本必须以'{'为1 [字符2第1行]开头”
这是我的代码:
public class Nethelper
{
public JSONObject uploadToServer() throws IOException, JSONException
{
String query = "http://validate.jsontest.com/?json=";
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");
String json = jsonObject.toString();
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(json);
osw.flush();
osw.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = convertStreamToString(in);
JSONObject jsonObjectres = new JSONObject(result);
in.close();
conn.disconnect();
return jsonObjectres;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
知道可能出现什么问题吗?我尝试了几种不同的方法,但都给出了同样的错误。
答案 0 :(得分:1)
是的,你需要正确发布你的json字符串 json的POST var:
String query = "http://validate.jsontest.com/";
// create the connection
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
// set up the data to send ("json=foobar")
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");
String urlParameters = "json="+ jsonObject.toString();
byte[] postData = urlParameters.getBytes("UTF-8");
int postDataLength = postData.length;
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
// write the postdata to the connection.
OutputStream osw = conn.getOutputStream();
osw.write(postData);
osw.flush();
osw.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = convertStreamToString(in);
JSONObject jsonObjectres = new JSONObject(result);
in.close();
conn.disconnect();
其他有用的信息:Java - sending HTTP parameters via POST method easily
答案 1 :(得分:-1)
你想要解析不正确的json格式。
杰森看起来像 http://contester.ddns.is74.ru:84/Get_all_users_list.ashx