Android https handshake terminated exception - java

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

Related

How to Authorization Bearer token in Java

I'm using Java 7.
I'm trying to access the API(https) using authorization bearer token in Java.
Here is the client code that I used:
public class HttpURLConnectionExample {
public static void main(String[] args) throws Exception {
try {
URL url = new URL("https://example-url.com/xxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer eyXXXXXX");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
// printing result from response
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Then I get the error response result:
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path validation
failed: java.security.cert.CertPathValidatorException: timestamp check
failed
How to solve it?
The API you are using needs a secure connection to do that import the certificate for the api into your jre location using keytool command

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

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)

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

Does closing of input/output stream gotten from getInput/OutputStream() affects recreation of underlying Socket?

I've already looked through resources which describe specifics of work with HttpURLConnection as in Java so in Android (where there is not default implementation of working with connection pool) and my question is: if I close a stream gotten from HttpURLConnection, will the system create a new one Socket at a next time when I establish a HttpURLConnection with the same URL or it will try to use an exist one? Considering the following code:
private byte[] downloadText(URL url, String data) {
OutputStream out = null;
InputStream in = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("POST");
conn.setReadTimeout(20 * 1000);
conn.setConnectTimeout(15 * 000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
byte[] payload = data.getBytes("utf-8");
conn.setFixedLengthStreamingMode(payload.length);
conn.connect();
out = new BufferedOutputStream(conn.getOutputStream());
out.write(payload);
out.flush();
final int responseCode = conn.getResponseCode();
final String responseMessage = conn.getResponseMessage();
is = conn.getInputStream();
if((responseCode / 100) == 2 || responseMessage.equals("OK")) {
return readFromStream(is);
}
} catch (IOException e) {
Log.e(TAG, "Error occurred while trying to connect to the server" + e.toString());
} finally {
try {
if(out != null) {
out.close();
}
if(is != null) {
is.close();
}
} catch(IOException e) {
Log.e(TAG, "Error occurred while trying to close data streams" + e.toString());
}
}
}
Your question doesn't make sense. If there isn't a connection pool, there is no 'existing socket' to reuse.

Categories