I have tried so many options, I'm going to go crazy. I continue to get an SSL exception every time I try to post to a URL.
This works like a dream in C# using an HttpWebRequest.
The errors I get are:
Not trusted server certificate
java.security.cert.CertPathValidatorException: TrustAnchor for CertPath not found.
I am trying the following approach now, but I have tried custom SocketFactories, everything. Please help!
final String httpsURL = "https://...";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);
//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("mail", username));
nvps.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity p_entity = null;
try {
p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
httppost.setEntity(p_entity);
//sending the request and retrieving the response:
HttpResponse response = null;
try {
response = client.execute(httppost, _context);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity responseEntity = response.getEntity();
//handling the response: responseEntity.getContent() is your InputStream
try {
final InputSource inputSource = new InputSource(responseEntity.getContent());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You need to consider how Android determines the validity of certificates. When it needs to verify a certificate, it will look at the chain of signatures. If it can find a trusted authority at its top, and the certificate not being on the revocation list, then it will be trusted.
To reduce time-intensive queries, Android comes bundled with a list of common CAs that it trusts. As you noted in the comments, the error disappeared when you upgraded. This is most likely due to the CA you were using being added to the list of shipped trusted CAs.
You can, if you trust the certificate, add it to this list of trusted CAs. The accepted answer to this question has some details on this procedure for older versions! Newer versions are more likely to come shipped with the certificates you will need. With newer versions, you can install certificates directly from your SD card. Go to Settings -> Security. Under Credential storage you will find the option Install from device storage. As long as you are using a standard format, you should be able to install your certificate!
My source: Security with HTTPS and SSL | Android Developers
Related
I have written a Android program to upload a file to server by HTTP POST.
Earlier its was working fine but I don't know why it is not working now.
I am testing this with my Android Device.
I Have just checked that It is working fine with emulator.
When I open that link in browser, Then it is still working fine and open correctly.
Do any body can tell me what could be the problem???
I am getting this error: (No Address associated with hostname)
10-07 04:28:14.410: I/System.out(1280): executing request POST http:////path/to/my/server//api/index.php/match HTTP/1.1
10-07 04:28:14.450: W/System.err(1280): java.net.UnknownHostException: Unable to resolve host "//path/to/my/server/": No address associated with hostname
Here is my code...
private class UploadFilesTask extends AsyncTask<File, Void, Void> {
#Override
protected Void doInBackground(File... arg0) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
enter code here
// I have not shown my REAL server address due so some restriction, So assume below URL is correct
HttpPost httppost = new HttpPost("http://path/to/my/server/"); //Assume path is correct
//File file = new File("/mnt/sdcard/DCIM/Camera/01.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(arg0[0], "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
try {
//audioFilename = EntityUtils.toString(resEntity);
System.out.println(EntityUtils.toString(resEntity));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resEntity != null) {
try {
resEntity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
httpclient.getConnectionManager().shutdown();
return null;
}
}
Try the following
Delete your AVD
Shut down Eclipse
Created the AVD via the command line (e.g. android create avd -n my_android1.5 -t 2)
Launched it from the command line with the option -dns-server 8.8.8.8 (e.g. emulator -avd my_android1.5 -dns-server 8.8.8.8)
p.s. Make sure you didn't delete the internet permission in your manifest file by accident. Also, while you are it, check and make sure the address work on your android browser.
Try flush DNS. (in windows: ipconfig /flushdns)
Or change DNS provider.
Maybe there is a 2 '/' simbols in url ? "...server//api..." this must be like this "...server/api..."
My twitter android app is clent base means window base,I am using twitter 4j otweet.com for my my application.I stored Auth token through shared prefrence.I am getting error in logcat..that is.. twitter4j.TwitterException: Read error: Failure in SSL library, usually a protocol error.
And my code is:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api.otweet.com/1/account/end_session.format");
try {
// Execute HTTP Post Request
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Visit the following link
http://blog.doityourselfandroid.com/2011/02/13/guide-to-integrating-twitter-android-application/
i am making google calendar application in android and i don't know how to use google Authorization service in our android application?
This project describes google auth and this tutorial for calendar.
check the OAuth concept in this you can implement by this OAuth.
check this post links
Android Google Calendar Authorization Problem
Synchronising Google Calendar to my application in Android
Google calendar: how to access it on android
http://code.google.com/p/google-api-java-client/wiki/Android
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("<URL HERE>");
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>(2);
parameters.add(<name_value_pair>);
parameters.add(<name_value_pair>);
httppost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpclient.execute(httppost);
StatusLine returned_status = response.getStatusLine();
int status_code = returned_status.getStatusCode();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I m implementing android app in that I m working on web api. Sometimes my app gets connected to webserver but sometimes it throws exception as java.net.UnknownHostException: Host is unresolved: webservername.com:80. I m fetching json response from api.
I m using fetching code as following:
String queryResult = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI(archiveQuery));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpResponse response = client.execute(request, new BasicResponseHandler());
try {
queryResult = client.execute(request, new BasicResponseHandler());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think it's a DNS issue of your server, according to your comments. Sometimes you ping, sometimes you don't, but on your browser it always work? Surely it's a server connectivity issue.
The Answer is really very simple. You need to Restart the emulator.Check out this
Just restart adb, find adb.exe in your adt bundle and double click it. Some shit will happen on command prompt, and there you go, restart your emulator and it should work fine,
I'm building an android app which should perform a GET on my site to get two cookies and then perform a post to the same site with these cookies.
As mentioned I start of with the GET and I'm using org.apache.http.client.HttpClient to perform this operation.
String requiredCookies = "";
HttpContext localContext = null;
System.out.println("------------------GET----------------------");
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("www.mysitegeturl.com");
//Creating a local instance of cookie store.
CookieStore cookieJar = new BasicCookieStore();
// Creating a local HTTP context
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);
HttpResponse response;
try {
response = httpClient.execute(get, localContext);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
//Do this so that Java.net impl should work
List<Cookie> cookies = cookieJar.getCookies();
for (int i = 0; i < cookies.size(); i++) {
requiredCookies += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("------------------GET-END---------------------");
So far so good. Don't mind the requiredCookies line yet, it will be used in the Java.net impl since I can't get the HttpClient one to work =(.
Let's take a look at the non working HttpClient Post part.
System.out.println("------------------HttpClient - POST----------------------");
HttpPost post = new HttpPost("www.mysiteposturl.com");
//Params
HttpParams params = new BasicHttpParams();
params.setParameter("foo", "post");
params.setParameter("bar", "90");
params.setParameter("action", "search");
post.setParams(params);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
HttpResponse response2 = httpClient.execute(post, localContext);
System.out.println(response2.getStatusLine());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------POST END---------------------");
What happens now is that I perform a POST with the localContext where the cookies are stored. This doesn't work. I get a HTTP/1.1 401 No session. Since I had no luck with this I tried another approach(java.net.HttpURLConnection). Remember I still use the same GET part
URL url = new URL("www.mysiteposturl");
HttpURLConnection connection = null;
String dataString = "bar=90&foo=post&action=search";
try {
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Cookie", requiredCookies);
//Set to POST
connection.setDoOutput(true);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(dataString);
writer.flush();
writer.close();
connection.connect();
if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {
System.out.println(connection.getContent().toString());
} else {
System.out.println("Error");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------POST END---------------------");
And VIOLA a 200 is displayed and everything works like a charm. What do you guys think? Could someone please provide me with an answer because I can't figure it out.
The problem appears to be that you have two different host names in the setup. This will cause HTTP Client to not send cookies for a different host. You could try changing the domain of the cookies in the cookie store, or using the same host for GET and POST. Additionally you could manually add the cookies to the headers in HTTP Client as you did in the HttpURLConnection example.
I guess it was a mistake that you used two completely different domains for your two requests — i.e. you were trying to mask your real URL? If not, then that's why you're not getting any cookies. If were just trying to mask your URL, well that's why example.com exists. :)
Alternatively, and this is completely off the top of my head from code I wrote last week — it worked fine across multiple GETs, POSTs and subdomains:
DefaultHttpClient httpClient = new DefaultHttpClient();
CookieStore cookieJar = new BasicCookieStore();
httpClient.setCookieStore(cookieJar);
i.e. I'm explicitly using a DefaultHttpClient, which I believe has those extra get/setters for the cookie store. I don't think I used any context objects either.