I want to read a xml from a service url, I wrote the code, my url is ok, seen from browser,
public String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://localhost/simplewebservice/index.php?user=1");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (Exception ex) {
Log.d("Error reading xml", ex.toString());
}
return line;
}
But it gives me the following error java.net.SocketException: Permission denied.
Can anyone have a better solution for this?
Kind regards,
Pritom.
in your manifest.xml add this description
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
I am sure that your using emulator.
Andriod emulator is separate virtual machine by itself. If we provide localhost/127.0.0.1 as a hostname, then emulator will try to search url within its environment. To avoid this problem, we need to provide the ipaddress of local machine.
Pls note that machine name as a hostname will also give problem.
127.0.0.1 refers to localhost in the Emulator, not your machine.
Use 10.0.2.2 to connect to your host machine.
Related
I try to connect MySql.And can use the PostMan get data from 192.168.56.1:8080/BookBankService/rest/api/getall and when I use chorme in genymotion browse 192.168.56.1:8080/ can see the tomcat page. But when I test my code the result return null. And when I use debugger I can see the postRequest url is 192.168.56.1t:8080/BookBankService/rest/api/getall
(Ingore locahost mean 192.168.56.1 here)
public static String post(String url, String json) {
LocalhostURL ="http://192.168.56.1:8080/BookBankService/rest/api"
String result = "";
try {
String strRequest = LocalhostURL + url;
HttpPost postRequest = new HttpPost(strRequest);
postRequest.setHeader("Content-type", "application/json");
postRequest.setHeader("accept", "application/json");
postRequest.setHeader("accept","text/plain");
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
postRequest.setEntity(s);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
Android Http request must be executed in AsyncTask or Handler.
If none, then you'll try to get the result before the execute returned a value.
Take a look at a class i created.
Java : a WebService asking embeded in a AsyncTask
where do you are testing your code?
If you're testing it in an emulator you have to replace "localhost" with "10.0.0.2" that is the IP address of the host machine.
For further info please read here: http://developer.android.com/guide/faq/commontasks.html - section "Referring to localhost from the emulated environment"
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
This must be something really stupid, trying to solve this issue for a couple of days now and it's really not working. I searched everywhere and there probably is someone with the same problem, but I can't seem to find it.
I'm working on an Android app and this app pulls some xml from a website. Since this website is down a lot, I decided to save it and run it locally. Now what I did:
I downloaded the kWs app for hosting the downloaded xml file.
I put the file in the right directory and could access it through the mobile browser, but not with my app (same code as I used with pulling it from some other website, not hosted by me, only difference was the URL obviously).
So I tried to host it on my PC and access it with my app from there. Again the same results, the mobile browsers had no problem finding it, but the app kept saying 404 Not Found: "The requested URL /test.xml¶ma=Someone¶mb= was not found on this server."
Note: Don't mind the 2 parameters I am sending, I needed that to get the right stuff from the website that wasn't hosted by me.
My code:
public String getStuff(String name){
String URL = "http://10.0.0.8/test.xml";
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("parama", name));
params.add(new BasicNameValuePair("paramb", ""));
APIRequest request = new APIRequest(URL, params);
try {
RequestXML rxml = new RequestXML();
AsyncTask<APIRequest, Void, String> a = rxml.execute(request);
...
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
That should be working correctly. Now the RequestXML class part:
class RequestXML extends AsyncTask<APIRequest, Void, String>{
#Override
protected String doInBackground(APIRequest... uri) {
HttpClient httpclient = new DefaultHttpClient();
String completeUrl = uri[0].url;
// ... Add parameters to URL ...
HttpGet request = null;
try {
request = new HttpGet(new URI(completeUrl));
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
HttpResponse response;
String responseString = "";
try {
response = httpclient.execute(request);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
// .. It crashes here, because statusLine.getStatusCode()
// returns a 404 instead of a 200.
The xml is just plain xml, nothing special about it. I changed the contents of the .htaccess file into "ALLOW FROM ALL" (works, cause the browser on my mobile device can access it and shows the correct xml).
I am running Android 4.0.4 and I am using the default browser AND chrome on my mobile device.
I am using MoWeS to host the website on my PC.
Any help would be appreciated and if you need to know anything before you can find an answer to this problem, I'll be more than happy to give you that info.
Thank you for you time!
Cheers.
I think you just miss the question mark after your filename
/test.xml?¶ma=Someone¶mb=
so this is for a project im doing for my school in which we need a backend.
our current setup is that the foreground is an android app, whereas the backend is a mySQL database that is located within my school's servers. The android app is supposed to interact with the mySQL database using a php script.
my php script is set currently hardcoded to return one single row from the mySQL database in JSON format.
my android code is as follows:
public static final String KEY = "URL of my PHP script";
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(KEY));
Log.d(null,"there");
HttpResponse response = httpclient.execute(request);
Log.d(null, "here");
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
However, I get an exception at the line
HttpResponse response = httpclient.execute(request);
in which the error says: No Peer Certificate.
Anyone know what's wrong with it, and how to fix it?
I have the same issue. This link worked for part of my needs.
http://www.knowledgebit.appspot.com/zahangirbd/TopicView.action;jsessionid=E2BZt_6bp4uFFbMyq42gWg?id=56001
however, there is still an issue with some links(i believe im not providing the proper certificate)
EDIT: so it turns out that the order of the certificates were the problem.
check this out, this helped me..
Apache HttpClient on Android producing CertPathValidatorException (IssuerName != SubjectName)
I am parsing an xml file.
One of the method is below :
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://p-xr.com/xml/");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
Here, I want to replace
HttpPost httpPost = new HttpPost("http://p-xr.com/xml/");
by
HttpPost httpPost = new HttpPost("http://127.0.0.1/myfile.xml");
As i can browse http://127.0.0.1/myfile.xml in my browser.
But when i write this address to above code it doenst work.
why ?
My project requires http method to access xml file.
In emulator the localhost is the emulator itself not your system which runs the emulator. So it will not work.
Use 10.0.2.2 instead.
Use 10.0.2.2 in this case, check out Emulator Networking.
In the emulator there are some specially defined address aliases used to access networks outside of the emulator itself.
To access localhost on the system running the emulator (ie. the host system), use 10.0.2.2
Reference here:
http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
If you're want to do this with an Android device:
You can find out the IP address of your computer by using ifconfig on Mac or Linux or ipconfig on Windows.
Then you can replace p-xr.com / 127.0.0.1 with that IP address.
You'll need to make sure that you don't have a firewall set up on your computer and if so, you'll have to allow access to your Android device in order to contact your local HTTP server.