i´am trying to send a JSON string over http via android and iam trying to validate it via http://www.jsontest.com/#validate .
I get the response:
"error": "A JSONObject text must begin with '{' at 1 [character 2 line 1]"
Here is my code:
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();
}
Any idea what could be wrong? I have tried several different ways but all gives the same error.