Unable to get response from HttpURLConnection POST method - java

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);
}

Related

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!!!

Passing json array in a key value pair in 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();
}

Print Wit.ai response in console [java]

hi all I'm trying to send a request to Wit to a simple wit application that i've created and I'm doing this in java. I'm trying to print the wit response into the console but the only thing that prints is the following line:
class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
The code that I am using to send the request is a code that I have found on this forum, I repost it for be more specific:
public static String getCommand(String command) throws Exception {
String url = "https://api.wit.ai/message";
String key = "MY_SERVER_KEY";
String param1 = "my_param";
String param2 = command;
String charset = "UTF-8";
String query = String.format("v=%s&q=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty ("Authorization", "Bearer " + key);
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
return response.toString();
}
how can i return the wit response?
EDIT:
I'm trying with apache as you suggested to me, but it keeps to send me error 400.
Here the code:
public static void getCommand2(String command) throws Exception {
String query = URLEncoder.encode(command, "UTF-8");
String key = "my_key";
String url = "https://api.wit.ai/message?v="+my_code+"q"+query;
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("Authorization: Bearer", key);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
}
You don't have to use Apache
Taken from the Wit.ai android-sdk.
public static String convertStreamToString(InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
is.close();
return sb.toString();
}
The problem you were having is that the InputStream's toString method is only returning it's class name. Another thing you can try is using HTTPURLConnection rather than just the simple URLConnection, since you know it will be an HTTP request as opposed to another protocol.

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.

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