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..."
Related
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
In Http Post, the values are not send to server. I got unknownhostexception at following line.HttpResponse rs=httpclient.execute(httppost);
http Coding:
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www.mysite.com/fasttrack/androidapps.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
appendLog("7)Value Encoded to url successfully");
HttpResponse rs=httpclient.execute(httppost); // unknownhostexception got
I added <uses-permission android:name="android.permission.INTERNET"/> in Manifestfile also...
Note : this codings works fine before I added log file codings...
my Log File coding is below:
public void appendLog(String text)
{
//File logFile = new File("alog.txt");
File logFile = new File("sdcard/alog.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sometimes the android emulator's browser stops working. So, try to restart your emulator from cmd like this,
run->cmd->your_sdk_path->tools->emulator -avd avd_name -dns-server 8.8.8.8
I have the following code which I use to send a request to the server.
String inputXML = createInputXML(searchText);
HttpClient httpclient = new DefaultHttpClient();
String url = "http://mysite.com/action";//Works fine if I use IP address directly,for eg:http://1.2.3.4/action
HttpPost httppost = new HttpPost(url);
HttpResponse response=null;
StringEntity se = null;
try {
se = new StringEntity(inputXML, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/xml;charset=UTF-8");
httppost.setEntity(se);
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();
}
When I run the program on emulator I am getting a UnKnownHostException on the line
response = httpclient.execute(httppost);
If I use the ip address directly instead of host name,the request is sent correctly.
Please note the following points:
I am using Android 2.3.3
I have added <uses-permission android:name="android.permission.INTERNET"></uses-permission> in the manifest xml
Proxy settings are updated in the emulator's APN.
Using the browser in the emulator I can access a website with their host names.
Any idea why this is causing an issue?
Please make sure, you followed all steps 1-4 user700284 described in his Question.
HttpClient client = new DefaultHttpClient();
//Get the default settings from APN (could be also hard coded stuff)
String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
//Set Proxy params of client, if they are not the standard
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpGet request = new HttpGet("http://www.google.com");
The url has nothing to do with the line
se = new StringEntity(inputXML, HTTP.UTF_8);
are you sure it is this line?
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.