SSLHandshakeException Unacceptable certificate because of device date time - android

When my app tried to connect internet I get following error message. The cause of this is the date time being incorrectly configured on the device.
Stack Trace :
javax.net.ssl.SSLHandshakeException: Unacceptable certificate: CN = COMODO ECC Domain Validation Secure Server CA 2, O = COMODO CA Limited, L = Salford, ST = Greater Manchester, C = GB
The following is the code that I use to connect. I want to connect internet without forcing user to change date time. Is it possible ? If possible , I will be gratefull if anyone helps me.
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestProperty("User-Agent", "");
connection.setRequestMethod("GET");
connection.connect();
InputStream is;
if (connection.getResponseCode() >= 400) {
is = connection.getErrorStream();
} else {
is = connection.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine()).append("\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
result = sb.toString();
Thanks alot.

Related

Get Request HttpUrlConnection - Incorrect response

I am working on an Android App, App is using GET Request to connect with server.
The code I have written to connect with server is working perfectly on many devices.
But its not giving good response on LENOVO YOGA TAB3, It returns Html tags instead of JSON text, Firstly I was confused that there may be some issue in the API URL but I checked URL using browser, Its returning good response so I am sure URL is correct.
Here are API URL and its response :
API URL
[http://www.xyz.in/xyzapi/?building=on&address=Assotech Sandal Suites, Sector 135, Noida, Uttar Pradesh 201304, India&bill_amount=12500&type=R&fullstatename=Uttar Pradesh&lat=28.496171099999998&lng=77.4027049&state=UP&country=IN&district=Gautam Buddha Nagar&sublocality=Sector 135&calc-sess=59d4beba305f3&netmetering=1][1]
Response on Many Android Phones:
{"lifetimesaving":"25.0 Lacs","proposed_pv_capacity":10,"billWithSolar":3872,"bill_amount":"12500","sanction":10,"project_cost":"6.0 Lacs","return_oninevstment":"20.8","roi_image":"solar_score6_6.png","treeadded":"346 ","treeofftheroad":"9 "}
Response on Lenovo Yoga Tab3:
<head/><style>.personal-details h2{font-size:34px}.netmetering-tgle{position:absolute;left:0;right:0;bottom:5px;width:211px}.netmetering-tgle .wnm{float:left;position:relative;padding:0 10px 0 0;min-width:130px;text-align:center}.netmetering-tgle .wnm a{color:#c97511;background:none}#radioBtn .btn{border:1px solid transparent;border-radius:0!important;font-family:"Din-Bold"}#radioBtn .notActive{color:#c97511;background-color:#e0e1e2;padding:2px 0;width:38px;background-size:100% 100%;border-color:transparent;font-family:"Din-Bold";border-radius:5px}#radioBtn .active{color:#fff;background-color:#addc6f;border-color:transparent;padding:2px 5px;width:38px;cursor:auto;pointer-events:none;border-radius:5px;box-shadow:inset 0 0 10px rgba(0,0,0,.8)}#radioBtn .notActive[data-
So response is incorrect on Yoga Tab3.
Here is the code I am using to connect with Server :
public static String connectToServerUsingGETMethod(String API_COMPLETE_URL){
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(API_COMPLETE_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
String line = "";
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
//get the string version of the response data
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return "";
}
Suggest me If I can add something in this code so that it can work on Yoga Tab 3 too.
I think you should set static content type when making request to make sure the response sent back is JSON. Similarly, it looks like below:
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Hope it works for you.

How to accept Self Signed Certificates on Android

After a couple of days of fruitless searching and trying various suggestions and examples im still struggling with this.
The situation is we are developing an Android app against a DEVELOPMENT system (ie not open to use outside IT). It has a self signed certificate. The live system will have a "proper" certificate so I dont really want to be disabling the certificate check just to develop it.
The error I am receiving is a 401 Authorization error. I have tried the request with the Authorization credentials through fiddler and the REST service is chugging away nicely.
The certificate is in the Trusted credentials store on the device under user.
Here is the code that makes the connection.
try {
StringBuilder pathName = new StringBuilder();
StringBuilder data = new StringBuilder();
pathName.append(getApiCall()+ path);
URL url = new URL(pathName.toString());
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(Proxy.NO_PROXY);
urlConnection.setRequestProperty("Autorization", getCredentials());
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json");
try
{
InputStream in = urlConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
while ( r.readLine() != null)
{
String dataLine = r.readLine();
data.append(dataLine);
}
}
catch (Exception ex2)
{
int freda = urlConnection.getResponseCode();
String fred = urlConnection.getResponseMessage();
data.append("ERROR");
}
finally
{
urlConnection.disconnect();
}
return data.toString();
}
catch (Exception e)
{
return "ERROR";
}
If anyone could point me in the right direction I would be extremely grateful.
Thanks
Steve

Android - How can I open a persistent HTTP connection that receives chunked responses?

I'm trying to establish a persistent HTTP connection to an API endpoint that publishes chunked JSON responses as new events occur. I would like to provide a callback that is called each time the server sends a new chunk of data, and keep the connection open indefinitely. As far as I can tell, neither HttpClient nor HttpUrlConnection provide this functionality.
Is there a way to accomplish this without using a TCP socket?
One solution would be to use a delimeter such as \n\n to separate each json event. You could remove blank lines from original json before sending. Calling setChunkedStreamingMode(0) allows you to read content as it comes in (rather than after the entire request has been buffered). Then you can simply go through each line, storing them, until a blank line is reached, then parse the stored lines as JSON.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(0);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sBuffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() == 0) {
processJsonEvent(sBuffer.toString());
sBuffer.delete(0, sBuffer.length());
} else {
sBuffer.append(line);
sBuffer.append("\n");
}
}
As far as I can tell, Android's HttpURLConnection doesn't support receiving chunks of data across a persistent HTTP connection; it instead waits for the response to fully complete.
Using HttpClient, however, works:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpUriRequest request = new HttpGet(new URI("https://www.yourStreamingUrlHere.com"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpClient.execute(request);
InputStream responseStream = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(responseStream));
String line;
do {
line = rd.readLine();
// handle new line of data here
} while (!line.isEmpty());
// reaching here means the server closed the connection
} catch (Exception e) {
// connection attempt failed or connection timed out
}

how I get the html source with utf-8 format?

I write this code to get html source from a site.
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "aranan="+et.getText();
try
{
url = new URL("http://www.fragmanfan.com/arama.asp");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
browser.loadDataWithBaseURL(null, response,"text/html", "UTF-8", null);
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}
});
But there is a one problem.It is : response (the variable that have html source) is not utf-8 format.
How I can fix this?
Thanks.
.
.
.
InputStreamReader isr = new InputStreamReader(connection.getInputStream(),"ISO-8859-9");
.
.
.
Since your response seems to be your HTML webpage in a single String, you should make sure that the head tag of your page cointains the label that defines the codification.. if not you can append it yourself to your StringBuilder.
Here is how you can do it:
final StringBuilder sb =
new StringBuilder("<html><head>"+ "<meta http-equiv=\"content-type\"content=\"text/html;charset=utf-8\" />"+ "</head><body>");
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
sb.append(response);
sb.append("</body></html>");
and then you can properly load your HTML to your webview / browser. (this worked for me so I know for sure that it actually works =] )
p.d. make sure to accept the answer that properly answer your question so people keep answering your future questions.
https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work

Getting atomic time with Android

I am using the following code to connect and retrieve the UTC time from an AtomicTime server from an Android device:
public static final String ATOMICTIME_SERVER="http://132.163.4.101:13";
BufferedReader in = null;
try
{
URLConnection conn = new URL(ATOMICTIME_SERVER).openConnection();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String atomicTime;
while (true)
{
if ( (atomicTime = in.readLine()).indexOf("*") > -1)
{
break;
}
}
... do something
}
catch ...
It does not return any data. When accessing the URL from a browser, we get the following:
55884 11-11-19 07:40:22 00 0 0 824.5 UTC(NIST)
Can anyone help?
String atomicTime = "";
try
{
Socket socket = new Socket("132.163.4.101", 13);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
in.readLine(); // Ignore leading blank line
atomicTime = in.readLine();
socket.close();
}
catch....
This is because there is no HTTP service on TCP port 13. There is daytime service. You should use Socket instead of URLConnection. Or maybe find some NTP implementation for Android.

Categories

Resources