Reputation: 91
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.
Upvotes: 0
Views: 73
Reputation: 17140
Yea, you need to properly post your json string with POST var of json:
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();
other helpful info here : Java - sending HTTP parameters via POST method easily
Upvotes: 1