Passing json array in a key value pair in Java - java

I'm trying to send data using rest webservice in Java. I'm able to post data using Java in POST but now I need to send data in rawModeData and I also need to send JSONArray in surveysData key.
Please find the attached screenshot
This is the Code that I'm using to send data
try {
URL url = new URL(webServiceData.getSyncSurveyDataUrl());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// ConnectionType
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Create the output form content
OutputStream out = httpURLConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
JSONObject objects = new JSONObject();
objects.put("constituency", constituency);
objects.put("longitude", longitude);
objects.put("latitude", latitude);
objects.put("createdOn", createdOn);
for (Map.Entry<String, String> map : linkedHashMap.entrySet()) {
objects.put(map.getKey(), map.getValue());
}
writer.write("createdByDeviceId");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getDeviceId(), "UTF-8"));
writer.write("&");
writer.write("createdByMobileNumber");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getMobileNumber(), "UTF-8"));
writer.write("&");
writer.write("state");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getLoggedInState(), "UTF-8"));
writer.write("&");
writer.write("eventId");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getEventId(), "UTF-8"));
writer.write("&");
writer.write("surveysData");
writer.write("=");
writer.write(URLEncoder.encode(objects.toString(), "UTF-8"));
if (httpURLConnection.getResponseCode() != 200) {
System.out.println("Exception in 200: " + httpURLConnection.getResponseCode());
System.out.println("Exception Message: " + httpURLConnection.getResponseMessage());
/*errorLabel.setText(httpURLConnection.getResponseMessage());
errorLabel.setVisible(true);*/
}
} catch (Exception e) {
return false;
}
I'm getting 401 error message

I think you missed some authentication token in headers. Something like : httpURLConnection.setRequestProperty("tokenKey", "yourAuthToken");

You are not connecting to connection. Also I think that you need to setFixedLengthStreamingMode on connection and write output as byte array. Example:
//...
String queryParameters = formatQueryParameters(requestData);
byte[] output = queryParameters.getBytes(Charset.forName("UTF-8"));
connection.setFixedLengthStreamingMode(output.length);
connection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(output);
//...
public static String formatQueryParameters(Map<String, String> requestData) throws UnsupportedEncodingException {
String equals = URLEncoder.encode("=", "UTF-8");
String ampersand = URLEncoder.encode("&", "UTF-8");
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : requestData.entrySet()) {
String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
String encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8");
builder.append(encodedKey).append(equals).append(encodedValue).append(ampersand);
}
builder.deleteCharAt(builder.lastIndexOf(ampersand));
return builder.toString();
}

Related

Unable to get response from HttpURLConnection POST method

I've seen multiple threads for this issue but unfortunately I couldn't figure out how to solve my problem from them.
Need help to find out how to fix my Java code, as you can guess my coding skills are still limited.
Managed to find solutions for "GET" & "DELETE" methods.
There is a sample written in C# & CURL but my skills are limited to interpret parts of the code.
https://github.com/tradeio/api-csharpclient/blob/master/Tradeio.Client/TradeioApi.cs
Here is my Java implementation:
public String PlaceOrder(String symbol, String side, String type, String quantity, String price) throws MalformedURLException, IOException {
LinkedHashMap<String, String> form = new LinkedHashMap<String, String>();
form.put("Symbol", symbol);
form.put("Side", side);
form.put("Type", type);
form.put("Quantity", quantity);
form.put("Price", price);
form.put("ts", String.valueOf(System.currentTimeMillis()));
return signAndSend2("/order", form, "POST");
}
private String signAndSend2(String url, LinkedHashMap<String, String> payload, String method)
throws MalformedURLException, IOException {
String nonce = String.valueOf(System.currentTimeMillis());
String baseUrl = UrlTradeio.urlV1;
String sign = "";
HttpURLConnection conn = null;
JSONObject json = new JSONObject(payload);
String formForPayload = json + "";
StringBuilder sb = new StringBuilder();
for (Entry<String, String> param : payload.entrySet()) {
if (sb.length() != 0)
sb.append('&');
sb.append(URLEncoder.encode(param.getKey(), "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = sb.toString().getBytes("UTF-8");
int postDataLength = postDataBytes.length;
// System.out.println(sb);
// System.out.println(formForPayload);
sign = hmac512Digest(formForPayload, TRADEIO_SECRET_KEY).toUpperCase();
conn = (HttpURLConnection) new URL(baseUrl + url).openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Sign", sign);
conn.setRequestProperty("Key", TRADEIO_API_KEY);
conn.setRequestProperty("ts", nonce);
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setRequestMethod(method);
conn.getOutputStream().write(postDataBytes);
conn.connect();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder output = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String responseBody = output.toString();
return responseBody;
}
Depending on what I try I have several error messages.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.exchange.trade.io/api/v1/order
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
at Private.TradeioApi.signAndSend2(TradeioApi.java:223)
at Private.TradeioApi.PlaceOrder(TradeioApi.java:113)
at test.main.main(main.java:37)```
I managed to solved the issue. Removed this:
conn.getOutputStream().write(postDataBytes);
And send the request like this:
try(OutputStream os = conn.getOutputStream()) {
os.write(postDataBytes);
}

HTTPS request containing BASE64 encoded string as parameter working fine from POSTMAN but not from java code even though it is URL encoded

I need to POST a request containing BASE64 encoded string as parameter. When I am trying from POSTMAN , it is working fine but from the java code , it is not working. My Java code is as follows:
URL url = new URL(requestURL);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setReadTimeout(timeoutVal);
conn.setConnectTimeout(timeoutVal);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
HashMap<String, String> postParams = new HashMap<String, String>();
String reqParam = Base64.getMimeEncoder().encodeToString((<Test>Value</Test>).getBytes());
postParams.put("param1", reqParam);
postParams.put("param2", "A");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(),"UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(),"UTF-8"));
}
return result.toString();
}
The code works fine if there is no Base64 encoded parameter.
Please help!!!

POST params empty, what am I doing wrong? HttpURLConnection / Android / Java

The code below shows a method, downloadUrl(), that takes a String, "myurl," its parameter. There are only two possible urls that I ever send to it, and the behavior of the method is different for each.
when myurl = URL1, it uses a GET request and everything works fine.
when myurl = URL2, however, it uses a POST request, and the response from the php page indicates that the post parameters sent with the request were empty. You can see the line where I set the POST params, so I don't understand why it's sending no params?!
Thanks for any help!
-Adam.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
String response = "";
try {
URL urlObject = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection();
// find out if there's a way to incorporate these timeouts into the progress bar
// and what they mean for shitty network situations
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
// INSERTED QUICK CHECK TO SEE WHICH URL WE ARE LOADING FROM
// it's important because one is GET, and one is POST
if (myurl.equals(url2)){
Log.i(TAG, "dlurl() in async recognizes we are doing pre-call");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String postParams = "?phone=" + phone;
writer.write(postParams);
Log.i(TAG, "we're adding " + postParams + "to " + urlObject);
writer.flush();
writer.close();
os.close();
}
else {
conn.setRequestMethod("GET");
conn.connect();
}
// Starts the query
int responseCode = conn.getResponseCode();
Log.i(TAG, "from " + myurl + ", The response code from SERVER is: " + responseCode);
is = conn.getInputStream();
// Convert the InputStream into a string
// i guess we look up how to do this
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "from downloadUrl, php page response was not OK: " + responseCode;
}
// it's good to close these things?
is.close();
conn.disconnect();
Log.i(TAG, "response is " + response);
return response;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
try with following code block to send parameters of the POST request.
Map<String,String> params = new LinkedHashMap<>();
params.put("phone", "phone");
StringBuilder postPraamString = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postPraamString.length() != 0) postPraamString.append('&');
postPraamString.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postPraamString.append('=');
postPraamString.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
writer.write(postDataBytes);
So I figured out the root of the problem...
In the line:
String postParams = "?phone=" + phone;
The problem was that leading question mark. The question mark should only be used in GET requests.

Not able to execute URL with json value in JAVA API springs

I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE

Neo4j Rest Calls Using Java( not in embedded mode)

I am actually using the community plugin in Neo4j and trying to make POST requests through java to query neo4j server.
I am always getting a java.io.IOException: Server returned HTTP response code: 400
While similar calls to the same url work through javascript, but the business logic suggests making calls through java.
Here is my code snippet:
String baseURL="ip_of_server";
StringBuilder builder = new StringBuilder();
try {
URL url = new URL(baseURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
OutputStream os=connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os,Charset.forName("UTF-8"));
System.out.println(url);
Map<String, Object> params = new HashMap<String, Object>();
params.put("query", "start x = node(3) return x");
HashMap<String,String> test3= new HashMap<String,String>();
params.put("params", test3);
ObjectMapper temp = new ObjectMapper();
String testString= temp.writeValueAsString(params);
writer.write(testString);
writer.close();
os.close();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println("Response from server for request : " + url.toString() + " is " );
System.out.println(builder.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Any suggestions?
What it requires is a parser, since '=' etc are converted by the encoding into other characters, hence neo4j throws an error

Categories

Resources