java.lang.RuntimeException: Failed : HTTP error code : 400 - java

I am trying to post a json data to a URL, I have no idea where my code went wrong, I am getting Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400 It would be of great help if anyone could help me outwith this issue.
Using postman I can perform the post operation, but through code it always throws 400.
I tried searching many posts but none of them work, I am stuck with this error.
try {
URL url = new URL("https://XXX/approvals");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("APIKEY", "abc");
conn.setRequestProperty("Authorization","Bearer abc");
String input = "{\"users\":\"100\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Error:
Post parameters : {"users":"100"}
Response Code : 400
java.lang.RuntimeException: Failed : HTTP error code : 400Cannot Estabilish Connection Failed : HTTP error code : 400
at com.Test.main(Test.java:46)

Related

can't reset method:already connected error at rest get service

I know this question has been asked many times I am writing it because I could not see an exact answer for that question. When I use following get service I get "java.net.ProtocolException: Can't reset method: already connected".
You can see the snippted below. For privacy reasons , I cannot share the get request link.
Thank you guys
try {
URL url = new URL("https://......");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() == 200) {
return true;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Android https handshake terminated exception

I'm getting this exception randomly when trying to make https request, sometimes it works and sometimes failed to make handshaking with this exception.
And I'm trying with lollipop and marshmallow.
javax.net.ssl.SSLProtocolException:
SSL handshake terminated: ssl=0x9d397c00: Failure in SSL library, usually a protocol error
error:100c543e:SSL routines:ssl3_read_bytes:TLSV1_ALERT_INAPPROPRIATE_FALLBACK (external/boringssl/src/ssl/s3_pkt.c:972 0x9b0bb3e0:0x00000001)
Here's how I'm making the requests
URL url;
HttpURLConnection connection;
try {
String serverUrl = "...";
url = new URL(serverUrl);
connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.i(TAG, "OK");
Log.i(TAG, "response " + in.readLine());
} else {
Log.e(TAG, "Error " + responseCode);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}

Getting Network is unreachable on IPV6 Network

I am getting "Network is Unreachable" from below Java Http request for any url.
Below code is working fine with IPV4 network.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this issue.
If you are specifying the IPv6 URL using the IP address, you need to enclose it in square brackets since the :: in the address are special characters in a URL.
See RFC 2732.

Connection to distant server using HttpURLConnection

I try to send a json object to a distant server using HttpURLConnection.
but this error was displayed
"Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 401
at TestSendSMS.main(TestSendSMS.java:40)"
I didn't know what's the problem.What's wrong in this code? Any help
try {
/*
* JSONObject jsonParam = new JSONObject();
* jsonParam.put("-----","----"); jsonParam.put("----","-----");
* jsonParam.put("-----","-----");
*/
String input = "{\"------\":\"------\",\"-----\":\"------\",\"------\":\"-----\"}";
System.out.println("JsonObj " + jsonParam);
URL myURL = new URL("-----------------------");
HttpURLConnection myURLConnection = (HttpURLConnection) myURL
.openConnection();
myURLConnection.setDoOutput(true);
myURLConnection.setDoInput(true);
myURLConnection.setChunkedStreamingMode(0);
myURLConnection.setUseCaches(false);
myURLConnection.setConnectTimeout(10000);
myURLConnection.setReadTimeout(10000);
myURLConnection.setRequestProperty("Content-Type",
"application/json");
myURLConnection.setRequestProperty("Accept", "application/json");
OutputStream os = myURLConnection.getOutputStream();
os.write(input.getBytes());
os.flush();
if (myURLConnection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ myURLConnection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(myURLConnection.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
System.out.println("error1");
}
catch (IOException e) {
System.out.println("error2");
}
HTTP Error 401 is an authentication problem.
You need to authenticate to the server when sending the request.
This topic may help you authenticate with URLConnection :
How to handle HTTP authentication using HttpURLConnection?

connect failed: ECONNREFUSED HttpURLConnection POST internal server Android

My Native Android Application calls the web service hosted in my organization internal server which works in our network.
I am using Async task to do the HTTP POST connection using HttpURLConnection. When I do DataOutputStream wr = new DataOutputStream(conn.getOutputStream());, it is giving java.net.ConnectException: failed to connect to /10.xxx.xxx.xxx (port 90): connect failed: ECONNREFUSED (Connection refused)
try {
for (String currentUrl : urls) {
// 1. URL
URL url = new URL(currentUrl);
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(requestObject.toString());
wr.flush();
wr.close();
// 6. Get the response
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();
// 7. Print result
System.out.println(response.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Where I am going wrong ? Kindly suggest me

Categories