mark mark - 2 months ago 10
Java Question

JSON String using POST client

Hello all i am trying to capture the json "post" data from the client and send it to other client i.e i am trying to get the data of the client who hit my url and i handle this data and send it to the actual url.For this i have created an internal post client where i handle the data and send to my actual url.

URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String a = book.getId();
String b = book.getName();
String c = book.getAuthor();
String d = book.getPrice();

System.out.println(a + b + c + d);

byte[] out = "{\"id\":\"root\",\"name\":\"password\",\"price\":\"root\",\"author\":\"password\"}"
.getBytes();
int length = out.length;

conn.setFixedLengthStreamingMode(length);
conn.setRequestProperty("Content-Type",
"application/json; charset=UTF-8");
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(out);
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((output = br.readLine()) != null) {
response = output;
}
// return parseJSON(response);
return response;


I want to place my values of the strings a,b,c,d with the root,password,root,password respectively.

But when i try to place it i get the error insert missing quote.

Please help me regarding this

Thank you

Answer

Moving Comment to Answer as it worked for OP.

you can convert string to byte array as below:

byte[] request =  new String("{\"id\":\"" + a + "\",\"name\":\"" +b+"\",\"price\":\"" + c+" \",\"author\":\"" + d+ "\"}").getBytes() 
Comments