I'm trying to have my android app execute code where it opens a URL connection to a local php file that returns database entries in JSON format, but it's not connecting, after commenting out the other lines I can see that it throws an exception at the lines:
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Heres the screen shot of android code and the error log, the returned expected json file in windows and the php file:
link
Can you change your
URL url = new URL(getListUrl);
into
URL url = new URL("http://www.google.com");
and check the incoming data.
and the following is a working example.
try {
URL url = new URL("http://www.google.com");
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL Exception");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
My argument is if this code works for remote urls, it should work with localhost as well.
Hi it must be that you are using wrong local ip address in android files
it should be 10.0.2.2 not 127.0.0.1
First tell me are you testing on emulator or device
if emulator then where you define file path it should be
http://10.0.2.2/request_entries.php
just like in code
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/request_entries.php");
Managed to get the input stream using the URL:
URL url = new URL("http://10.0.2.2/request_entries.php");
result
Thanks a bunch guys :)
Related
How can I get POST request to work with an "https:" url?
In the following example when I set the URL to "https" instead of "http" the HttpURLConnection automatically makes my request a "GET" ?! while when it was a regular http request it was a POST...
URL url = new URL("*https:*//www.google.com");
// URL url = new URL("*http:*//www.google.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// readStream(in);
}finally {
urlConnection.disconnect();
}
enter image description here
Use HttpsURLConnection instead of HttpURLConnection
I am having trouble getting my app to open a connection to the URL that is a JSON file online. I followed guidelines how out to get the inBackground thread to fetch the URL, though when I call .connect() on that URL it seems to return out of the inBackground function because I tested just having a String that would be modified and displayed as a Toast, and modifying the String right after httpConn.connect() caused no change at all. I made sure my permissions were right in the manifest, but perhaps there is something small I am overlooking.
protected String doInBackground(URL... urls){
InputStream in = null;
String result = "test";
int responseCode = -1;
try {
URL url = urls[0];
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
result = "get here";
httpConn.connect();
result = "don't get here";
responseCode = httpConn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
httpConn.disconnect();
result = readIt(in, 10);
return result;
}
catch (Throwable t){
t.printStackTrace();
}
return result;
}
Any ideas of what is causing there not to be any connection or how to test if I am simply overlooking or not completely understanding this? I can additional code if needed. Thank you
As I am getting ,You want to connect to a web url which returns json response .Am I right ? If yes then you need to visit this link for complete solution .
I connect to two servers (PROD is https, test server is http) on my applicaitons.
on J2ME: I can connect to this two servers without a problem.
on Android I can't connect to test-server. When connection is http, if I dont use setChunkedStreamingMode, I cant get responseCode(StringIndexOutOfBoundsException); if I use setChunkedStreamingMode, response code is 401. What should I do, where is my fault??
Here is my android code, Also if you want to see J2me code, I can add it, too.
URL url = new URL(getUrl());
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setConnectTimeout(10000);
httpConn.setRequestProperty("User-Agent", util.getDeviceFullModel()
+ " " + util.getSoftwareVersion());
httpConn.setRequestProperty("Accept-Charset", "utf-8");
httpConn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction",
"http://tempuri.org/IAuthenticationServiceForGroup/"+conTypeString);
httpConn.setRequestProperty("Software-Version", AppData.VERSION);
httpConn.setChunkedStreamingMode(getParams().getBytes("UTF8").length);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.connect();
os = httpConn.getOutputStream();
os.write(getParams().getBytes("UTF8"));
try {
os.close();
} catch (Exception e) {
onError(e);
}
response=httpConn.getResponseCode();
J2ME code:
HttpConnection c = (HttpConnection)XConnection.openConnection(XConnection.SERVER + "AuthenticationServiceForGroup.svc");
c.setRequestProperty("User-Agent", XUtil.getDeviceFullModel() + " " + XUtil.getSoftwareVersion());
c.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
c.setRequestProperty("SOAPAction", "http://tempuri.org/IAuthenticationServiceForGroup/"+conType);
c.setRequestProperty("Software-Version", XApp.VERSION);
c.setRequestMethod(HttpConnection.POST);
OutputStream os = null;
os = c.openOutputStream();
os.write(sParams.getBytes());
try {os.close();} catch (Exception e) {}
if (c.getResponseCode() == HttpConnection.HTTP_OK)
If you're using pre-2.3 devices, HTTPUrlConnection has known issues
http://android-developers.blogspot.com/2011/09/androids-http-clients.html
I solved this problem. I use ip adress instead of link. Server was Sharepoint server so, It tries to connect to directly sharepoint server, so server wants Authentication:) Dont use directly ip:)
In my android application i have to get XML data from an URL(http://api.offersdb.com/distribution/beta/offers.json?api_key=demo&radius=10&postal_code=30305), for that i am using following code,
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}catch (Exception e) {
e.printStackTrace();
}
But it returns the following exception
java.net.UnknownHostException: Host is unresolved: api.offersdb.com:80
When i change the Host name (api.offersdb.com) with the ipaddress(XX.XX.XXX.XX) in the URL,i can get the response. I have no idea why i am getting this problem, please somebody help me.
Thanks in Advance,
Rajapandian
Have you tried to set the following permission in the manifest file?
<uses-permission android:name="android.permission.INTERNET" />
/ Alex
This means that name resolution is somehow broken on your device / the emulator. Are you able to use that URL from the built-in browser of your Android device?
I am using the code shown below to get Data from our server where Gzip is turned on. Does my Code already support Gzip (maybe this is already done by android and not by my java program) or do I have to add/change smth.? How can I check that it's using Gzip? For my opionion the download is kinda slow.
private static InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
if(in == null)
throw new IOException("No data");
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
Any modern http lib support Gzip compression, it's part of a standard for ages.
But you may need to send header : "Accept-Encoding: gzip"
You can check if it's really works using sniffer in your LAN, or on the Server. You can also check response headers, but that would require code changes (most likely, you will have to turn on gzip on your webserver).
Also, you may download 10Mb file of spaces. With gzip on it would be waaaaay faster :-)
When you using HttpURLConnection class to work with HTTP protocol "Accept-Encoding: gzip" field will automatically added to outgoing requests, and will handled the corresponding response.
(see documentation)