Test in emulator is ok, but it can not on phone - android

I test in emulator it can run correctly. But I test on the phone, it always throw an exception.
public static String doGet(String url) {
try {
HttpGet method = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
// HttpHost proxy = new HttpHost("10.0.0.172", 80); The two sentence added on the phone, it still can not run
// client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
method.setHeader("Connection", "Keep-Alive");
HttpResponse response = client.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK)
throw new Exception("");
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
return "Connection errors!";
}
}
I check API4 when create project. And test in emulator android 1.6. Test the phone is on android 2.3.3. I also test in computer android-x86 2.2 jars. It is no problem. I add <uses-permission android:name="android.permission.INTERNET"/> in AndroidManifest.xml. I do not know the reason. Anyone’s opinion is thankful.

What thread you call this function? You cant create connection in UI thread

Related

Android HTTPClient.execute stopped working after years

I have some Android applications that have not been touched in years. All of the sudden today they all stopped working. They all read data from a txt file that sits on an https:// site.
If I change the https:// call to http:// everything works fine again. I need the https:// for security. Can anyone tell me what happened?
Keep in mind that this application is a few years old. Did something change in an online library or something to break the https:// calls?
Here is the code. params[0] hold the website address. I have verified the address is correct. Just changing it to http:// fixes everything. II also know it is not the ssl certificate since I have verified it is all working.
It fails on the httpClient.execute command:
protected List<String> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(params[0]);
HttpResponse response;
List<String> data = new ArrayList<String>();
try {
response = httpClient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
data.add(line);
}
return data;
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
I don't have any logcat or console output that specifies what the error actually is. I could not find anything.
Thanks for any help.

UnknownHostException in version 4.1.2 in Android

I have an HTTP get Service url and i can connect and get resource from this url on almost all version of sdk but in 4.1.2 it gives UnknownHostException. Internet permission is already there and also internet connection is active. Please help.
Here is code:
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("myhosturl");
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
String response = EntityUtils.toString(resEntityGet);
}
}
catch (Exception e)
{
e.printStackTrace();
}
Actually this url is called when there is any incoming call that time it gives exception. If i hit this url any other time it works.

Sending JSON From Android to PHP

I've been struggling a bit on sending JSON objects from an application on android to a php file (hosted locally). The php bit is irrelevant to my issue as wireshark isn't recording any activity from my application (emulation in eclipse/ADK) and it's almost certainly to do with my method of sending:
try {
JSONObject json = new JSONObject();
json.put("id", "5");
json.put("time", "3:00");
json.put("date", "03.04.12");
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://localhost/datarecieve.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
I've modified this from an example I found, so I'm sure I've taken some perfectly good code and mangled it. I understand the requirement for multi-threading so my application doesn't hang and die, but am unsure about the implementation of it. Would using Asynctask fix this issue, or have I missed something else important?
Thankyou for any help you can provide.
Assuming that you are using emulator to test the code, localhost refers to the emulated environment. If you need to access the php hosted on your computer, you need to use the IP 10.0.2.2 or the LAN IP such as 192.168.1.3. Check Referring to localhost from the emulated environment
You can refer to Keeping Your App Responsive to learn about running your long running operations in an AsyncTask
you should use asynctask or thread, because in higher versions of android it doesn't allow long running task like network operations from ui thread.
here is the link for more description

Strange HttpResponse in Android

I am having an unusual problem regarding the following code in an android application.
public InputStream retrieveStream(String url) {
HttpGet request = new HttpGet(url);
HttpParams httpParams = new BasicHttpParams();
int some_reasonable_timeout = (int) (10 * DateUtils.SECOND_IN_MILLIS);
HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
HttpClient client = new DefaultHttpClient(httpParams);
try
{
HttpResponse response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK){
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
}
else
{
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
}
catch (ClientProtocolException e)
{
Log.e("Methods", "HTTP Error", e);
return null;
}
catch (IOException e)
{
Log.e("Methods", "Connection Error", e);
return null;
}
}
Within the application I attempt to connect to a localhost.(In an AsyncTask)
InputStream source = retrieveStream("http://10.0.2.2:27080/testdb/_hello")
When running on the emulator, this code works fine and if the localhost is down, "source" is returned as null as expected. Similarly when running the code on a mobile device (HTC Nexus One, Android Version 2.2), the code reports "source" as null as expected.
However when running the same APK on another mobile device (Samsung Galaxy S2, Android Version 4.0.3, samsung release), the status code returned is given as HttpStatus.SC_OK, even though it couldnt possibly be connecting to the localhost. Has anyone encountered a similar problem?
Android > 3.0 does not allow to execute web request on Main UI Thread. you need to use AsyncTask to make web request. IN android > 3.0

Android HTTP request wierd 404 not found issue

In my application, I am trying to hit a URL which I do using the following code
try {
url = new URL(serverURL);
httpURLConnection = (HttpURLConnection) url.openConnection();
int timeout = 30000;
httpURLConnection.setConnectTimeout(timeout);
httpURLConnection.setReadTimeout(timeout);
httpURLConnection.connect();
String httpResponseMessage = httpURLConnection.getResponseMessage();
responseCode = httpURLConnection.getResponseCode();
Log.i(LOG_TAG,"Response code "+responseCode);
} catch (Exception e) {
e.printStackTrace();
}
The (confidential) URL when opened through browser (on computer as well as on phone), works perfectly and the response is as expected. But when I hit the same URL via the above piece of code, it gives me response code 404 (NOT FOUND). Can anybody tell me what the issue can be?
(Sorry, can not post the URL since is highly confidential.)
Are you sure that you have the android.permission.INTERNET declared in your AndroidManifext.xml?
Problem solved :)
try {
url = new URL(serverURL);
Log.i(LOG_TAG, url+"");
HttpGet method= new HttpGet(new URI(serverURL));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));
HttpResponse response = client.execute(method);
responseCode = response.getStatusLine().getStatusCode();
Log.i(LOG_TAG,"Response code response "+response);
Log.i(LOG_TAG,"Response responseCode "+responseCode);
} catch (Exception e) {
e.printStackTrace();
}
Actually you don't even need following two lines in your code.
HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));
One HttpGet is enough and you don't need it twice.
Not sure if this matters but I had the exact problem.
I was doing some explicity port 80 stuff and removing this line made it work:
HttpHost host = new HttpHost(targetHost, 80, "http");

Categories

Resources