I'm trying to use HttpUrlConnection to send a POST. Everything seems fine but it keeps returns 400, as if the parameters are not sent in the DataOutputStream, or anyway sent in a malformed way.
public String doDBAuth(String dbURL, String dbUser, String dbPassword) throws IOException {
HttpURLConnection connection = null;
String res = null;
try {
BufferedReader reader;
StringBuffer buffer;
URL url = new URL(dbURL + "/auth");
connection = (HttpURLConnection) url.openConnection();
String urlParameters = "username=actn-admin&password=Test#&cliend_id=admin-cli&grant_type=password";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8 );
int postDataLength = postData.length;
connection.setRequestMethod("POST");
connection.setReadTimeout(40000);
connection.setConnectTimeout(40000);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setDoInput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
int responseCode = connection.getResponseCode();
int status = connection.getResponseCode();
InputStream inputStream;
if (status == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
reader = new BufferedReader(new InputStreamReader(inputStream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
res = buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
This is what is returned:
{"error":"unauthorized_client","error_description":"INVALID_CREDENTIALS: Invalid client credentials"}
This is weird cause this curl works properly:
curl --location --request POST '<URL>/auth' \
> --header 'Content-Type: application/x-www-form-urlencoded' \
> --data-urlencode 'username=actn-admin' \
> --data-urlencode 'password=Test#' \
> --data-urlencode 'client_id=admin-cli' \
> --data-urlencode 'grant_type=password' -k
and it returns me the access token I'm expecting
Keys and values need to be URL encoded (here's the spec).
Replacing "Test#" with "Test%40" should be enough in your example. For a future-proof solution you should encode all keys and values (e.g. with URLEncoder)
Related
I have a post API which doesn't accept any input. I have to get output from API. But it is giving compilation error.
HttpURLConnection connection = null;
String targetUrl="https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1/bots/"+BotID+"/dynamicEntities/"+dynamicEntityId+"/pushRequests
URL url = new URL(targetUrl);
connection=(HttpURLConnection) url.openConnection();
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2");
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
**osw.write();** //this line is expecting input in parameter
osw.flush();
osw.close();
os.close();
connection.connect();
If I dont pass any value in osw.write() it gives compilation error. How can I resolve the same.
Look at the following method for the post call. You will need to add the outputstream to the osw.write() as it expects a parameter.
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
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(response.toString());
}
else {
System.out.println("POST request not worked");
}
}
For more details on the above code look here.
I am calling REST service using java HttpURLConnection object.
When the HTTP server returns any business error, I am not able to retrieve the error properly.
For example, when I call the REST service through SoapUI, I get below error
<exception>
<errors>
<error>
<diagnostic>Matching item with shortCode = 1089992001234 found</diagnostic>
<field>shortCode</field>
<message>The Shortcode/CSG combination must be unique.</message>
<objectFailingValidationClass>com.axiossystems.assyst.dto.organisationConfiguration.SectionDto</objectFailingValidationClass>
<rule>isUniqueShortCodeWithCSG</rule>
</error>
</errors>
<message>A complex validation error has been detected by the application.</message>
<type>ComplexValidationException</type>
</exception>
But in the java code I getting below error, the request message format is correct
java.io.IOException: Server returned HTTP response code: 400 for URL: https://it-test.ihc.eu/assystREST/v2/sections
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1676)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1672)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at RestCaller.execute(RestCaller.java:59)
at RestCaller.main(RestCaller.java:18)
Can anyone let me know how to capture business error returned form server? Like the one received in SoapUI
Below is my code
try
{
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("accept", "application/xml");
String userpassword = username + ":" + password;
String authStringEnc = new String(Base64.encodeBase64(userpassword.getBytes()));
connection.setRequestProperty("Authorization", "Basic "+authStringEnc);
if (HttpMethod == "POST")
{
connection.setRequestMethod("POST");
//connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Type", "application/xml");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(payLoad);
writer.flush();
writer.close();
os.close();
}
int statusCode = connection.getResponseCode();
System.out.println("--------000----------" + statusCode);
InputStream is = connection.getInputStream();
System.out.println("--------111----------");
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
System.out.println("--------222----------");
String line;
System.out.println("--------333----------");
StringBuffer response = new StringBuffer();
System.out.println("--------444----------");
while ((line = rd.readLine()) != null)
{
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch (Exception e)
{
System.out.println("--------exception----------");
e.printStackTrace();
return "";
}
In case of error (i.e., httpStatusCode other than 200), you might have to read errorStream of HttpUrlConnection as below. After you read errorMessage, you could to deserialize it to the DTO that matches the xml output you pasted. Please note readErrorString() below is incomplete and expect you to use it for reference only
if (statusCode != 200) {
InputStream errorStream = connection.getErrorStream();
String errorMessage = (errorStream != null) ? readErrorString(errorStream) : connection
.getResponseMessage();
}
private void readErrorString(InputStream is) {
String responseString = null;
BufferedInputStream bis = null;
try {
StringBuilder sb = new StringBuilder();
bis = new BufferedInputStream(inputStream);
byte[] byteContents = new byte[4096];
int bytesRead;
String strContents;
while ((bytesRead = bis.read(byteContents)) != -1) {
strContents = new String(byteContents, 0, bytesRead, "UTF-8"); // You might need to replace the charSet as per the responseEncoding returned by httpurlconnection above
sb.append(strContents);
}
responseString = sb.toString();
} finally {
if (bis != null) {
bis.close();
}
}
}
return responseString;
400 error means your response data is malformed, means not in correct format. Please check again with your response api.
I'm sending a POST request to certain server.
I can send the date from curl like this:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://ictexpo.herokuapp.com/users -d "{\"user\":{\"name\":\"Choity\"}}"
But when I want to send the same data from java I don't get the outcome.
String urlParameters = "{\"user\" : {\"name\" : \"lssl\" }}";
URL url2 = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) url2.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Can anyone please tell me why I'm getting exceptopn?
I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...
I am making something for my HipChat room but for it to work i have to send a JSON request of:
POST /v1/rooms/message?format=json&auth_token=token HTTP/1.1
Host: api.hipchat.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 138
room_id=10&from=Alerts&message=A+new+user+signed+up
So far i have this:
public static void send(String send){
URL url = null;
HttpURLConnection conn = null;
try{
url = new URL("http://api.hipchat.com");
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "138");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream ());
wr.writeBytes (send);
wr.flush ();
wr.close ();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(line);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null) {
conn.disconnect();
}
}
}
But in the console it just returns null. How would i go about sending the above JSON request?
Thanks
Every time you loop here
while((line = rd.readLine()) != null) {
your line variable is replaced with the value returned by rd.readLine(). The last time it loops, that method call will return null. That's why line is null.
I'm going to assume you wanted to print out response.