JSON data missing while sending to server - java

When I parse an JSON object, it gets parsed easily and in the correct format. But as soon as I send the same thing to the server side, values go missing.
JSONArray check0 = new JSONArray();
JSONArray check1 = new JSONArray();
JSONArray check2 = new JSONArray();
check0.put(v11);
check0.put(v12);
check0.put(v13);
check1.put(c11);
check1.put(c12);
check1.put(c13);
check4.put(t11);
check4.put(t12);
check4.put(t13);
draft.put("check2",id11);
draft.put("check3",t11);
draft.put("check0",check0);
draft.put("check1",check1);
draft.put("check4",check4);
where v11,v12.......t12,t13 are string variables.
My code for sending data:
URL url = new URL("http://10.0.2.2:8080/initial");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new
DataOutputStream(connection.getOutputStream());
System.out.println(draft.toString());
dStream.writeBytes(draft.toString());
System.out:
{"Check1":["5","4","4"],"Check0":["6","44","4"],"Check2":"17082017123406","Check4":"1228123682","Check3":["4","4","4"]}
Code to receive the post request:
app.post('/initial', function(req, res){
console.log("POST received: "+ JSON.stringify(req.body));
res.end("cool");
});
Console output
POST received:
{"{\"Check1\":":{"\"5\",\"4\",\"4\"":{"\"6\",\"44\",\"4\"":{"\"4\",\"4\",\"4\"":""}}}}

try using the following
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Example
private JSONObject uploadToServer() throws IOException, JSONException {
String query = "https://example.com";
String json = "{\"key\":1}";
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");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(result);
in.close();
conn.disconnect();
return jsonObject;
}

Related

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

Sending a JSON formatted string through HttpUrlConnection

I've done some research on using HttpUrlConnect and most examples I've seen uses either
a) a params string which looks like this:
paramString = "param1=someParam&param2=2ndparam&param3=3rdparam";
b) uses a put method to place the parameters:
JSONObject json = new JSONObject();
json.put("param1", "Parameter");
json.put("param2", "Parameter2");
json.put("param3", "Parameter3");
The format I want to send looks like this:
{
"grant_type":"password",
"username":"testuser#someid.com",
"password":"testPwd123$"
}
Is there a way for me to send a formatted JSON string instead of setting parameters or using a param string? The code I'm using to send my POST request looks like the following:
public static String PostRequest(String urlString, String token, String jsonString) throws IOException {
byte[] postData = jsonString.getBytes(StandardCharsets.UTF_8);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty ("Authorization", "Bearer " + token);
conn.setUseCaches(false);
try( DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
int responseCode = conn.getResponseCode();
System.out.println("POST response code: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
I'm open to suggestions whether to use a different library, or if there are any code changes that I should make in order to take a JSON formatted string.

Send JSON data through POST in Java

I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
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");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.

In HttpURLConnection Why don't JSONObject as Params work but String as Params are working

I am using HttpUrlConnection to post some data to my server here is the function:
private String register(String myurl) throws IOException {
String resp = null;
try {
JSONObject parameters = new JSONObject();
// parameters.put("jsonArray", ((makeJSON())));
parameters.put("key", "key");//getencryptkey());
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds *///);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("strngbuffr" + response.toString());
resp = response.toString();
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
System.out.println("rsp"+ resp.toString());
return resp.toString();
}
I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here?
Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable key as "key"
Its amazing to see, this sample code works - sans the JSON array and the key value pairs:
private String sendPost(String url) throws Exception {
String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String urlParameters ="sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println("rvsp"+response.toString());
return response.toString();
}
So it boils down to replacing this:
JSONObject parameters = new JSONObject();
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("key", getencryptkey());
by this:
String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey();
and I am still curious.
I reckon the problem here is not at the Java side, If the parameters is of fixed type like in json in your case, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test response");
?>
The problem here was not with the Java side, it was with the php side, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test");
?>

Won't send all parameters to post http request

I am trying to send a http request with java. This is my code:
String AnnonseUrl = "http://webpage.no/insert_annonse.php?info="+info+"&tittel="+tittel+"&bedriftsNavn="+bedriftsNavn+"&kontaktEmail="+kontaktEmail+"&varighet="+varighet+"&frist="+frist+"&url="+url+"&sted="+sted+"&kontaktNavn="+kontaktNavn;
URL url = new URL(AnnonseUrl);
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
uc.getInputStream()));
in.close();
Only the first three parameters are submitted..
If I copie the string "AnnonseUrl" and paste it in to my browser, then everything works fine.
When doing a post the parameters are send in the Http Body:
Try this:
URL u = new URL("http://www.stackoverflow.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream (
conn.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
Where urlParameters is something like:
String urlParameters =
"tittel="+URLEncoder.encode(tittel,"UTF-8")
+"&bedriftsNavn"+URLEncoder.encode(bedriftsNavn,"UTF-8");

Categories