URL url = new URL(URL path);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(true);
connection.connect();
InputStream is = connection.getInputStream();
Above code is my code of Android.
I try to connect an URL path and get information to InputStream is.
I try to connect the same URL path with the same wifi by Android phone and iPhone.
Android phone spend about 10 seconds by moto phones or HTC phones.
But iPhone only spend less than 3 seconds.
I think it may not only cause by wifi speed.(Because I try with the same wifi).
So I want to ask that is it possible improved by code?
Try using the apache HttpClient instead of URL.openConnection()
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://your.url");
HttpResponse response;
try {
response = httpClient.execute(get);
InputStream is = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
Edit:
In API level 22 (Android M) the Apache HttpClient will be removed, so this approach is deprecated.
For more infor see :
http://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client
The recommended approach is to use HttpUrlConnection (http://developer.android.com/reference/java/net/HttpURLConnection.html):
URL url = new URL("http://your.url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Use volley it is an HTTP library that makes networking for Android apps easier and faster. Volley is available on GitHub. Volley may be able to help you streamline and improve the performance of your app's network operations.
Related
I am making a HttpUrlConnection with an Usgs API. This is my Url:
"https://earthquake.usgs.gov/fdsnws/event/1/queryformat=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10"
After thoroughly debugging, it seems that after connection.connect connection fails and jsonResponse is empty.
public static String makeHttprequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection connection = null;
InputStream stream = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(1000000);
connection.setConnectTimeout(1500000);
connection.connect();
stream = connection.getInputStream();
jsonResponse = readfromstream(stream);
} catch (IOException e) {
Log.e("IOException", "Error while making request");
}
return jsonResponse;
}
This is Log
Everything looks good. It seems to me that you have no internet connection in your running devices. Probably you are using emulator in your computer which is not connected to internet.
Please try to run in real device. It is working perfect for me.
A bit advice, please try to use libraries such as Retrofit or OkHttp. They are very much easier and handier than these old ways.
If you insist using HttpURLConnection, try the following
URL url = new URL(yourUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Or for more formal use of HttpURLConnection, visit here. It shows several proper use of HttpURLConnection APIs.
https://developer.android.com/reference/java/net/HttpURLConnection
just tried my app on real device everything is working as expected there might be problem with emulator.
I have a REST service I can't alter, with methods for uploading an image, encoded as a Base64 string.
The problem is that the images can go up to sizes of 5-10MB, perhaps more. When I try to construct a Base64 representation of an image of this size on the device, I get an OutOfMemory exception.
I can however encode chunks of bytes at a time (3000 let's say), but this is useless as I would need the whole string to create a HttpGet/HttpPost object:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.server.com/longString");
HttpResponse response = client.execute(httpGet);
Is there a way of going around this?
Edit: trying to use Heiko Rupp's suggestions + the android doc, I get an exception ("java.io.FileNotFoundException: http://www.google.com") at the following line: InputStream in = urlConnection.getInputStream();
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write("/translate".getBytes());
InputStream in = urlConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
System.out.println("response:" + total);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Am I missing something? The GET request that I need to execute looks like this:
"http://myRESTService.com/myMethod?params=LOOONG-String", so the idea was to connect to http://myRESTService.com/myMethod and then output a few characters of the long string at a time. Is this correct?
You should try to use the URLConnection instead of the apache http client, as this does not require you to hold the object to send in memory, but instead you can do something like:
pseudocode!
HttpUrlConnection con = restUrl.getConnection();
while (!done) {
byte[] part = base64encode(partOfImage);
con.write (part);
partOfImage = nextPartOfImage();
}
con.flush();
con.close();
Also in Android after 2.2 Google recommends the URLConnection over the http client. See the description of DefaultHttpClient.
The other thing you may want to look into is the amount of data to be sent. 10 MB + base64 will take quite a while to transfer (even with gzip compression, which the URLConnection transparently enables if the server side accepts it) over a mobile network.
You must read docs for this REST service, no such service will require you to send such long data in GET. Images are always sent as POST. POST data is always at the end of request and allows to be added iteratively.
I have a code to perform POST Requests with HttpsUrlConnection, the code works fine, but some of my Users have SIM Cards with a closed Usergroup and they need to set a proxy in the settings of their apn. If they set the proxy, i need to modify my code. I Tryed this:
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = "https://xxx";
String boundary = "*****";
try {
URL url = new URL(urlServer);
SocketAddress sa = new InetSocketAddress("[MY PROXY HOST]",[My PROXY PORT]);
Proxy mProxy = new Proxy(Proxy.Type.HTTP, sa);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + boundary);
//this is supposed to open the connection via proxy
//if i use url.openConnection() instead, the code works
connection = (HttpsURLConnection) url.openConnection(mProxy);
//the following line will fail
outputStream = new DataOutputStream(connection.getOutputStream());
// [...]
} catch (Exception ex) {
ret = ex.getMessage();
}
now i receive the error:
javax.net.ssl.SSLException: Connection closed by peer
If i use url.OpenConnection() wuithout Proxy and without Proxysettings in the apn, the code works, what might be the Problem?
You could try this alternative way of registering a proxy server:
Properties systemSettings=System.getProperties();
systemSettings.put("http.proxyHost", "your.proxy.host.here");
systemSettings.put("http.proxyPort", "8080"); // use actual proxy port
You can use the NetCipher library to get easy proxy setting and a modern TLS config when using Android's HttpsURLConnection. Call NetCipher.setProxy() to set the app-global proxy. NetCipher also configures the HttpsURLConnection instance to use the best supported TLS version, removes SSLv3 support, and configures the best suite of ciphers for that TLS version. First, add it to your build.gradle:
compile 'info.guardianproject.netcipher:netcipher:1.2'
Or you can download the netcipher-1.2.jar and include it directly in your app. Then instead of calling:
HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection(mProxy);
Call this:
NetCipher.setProxy(mProxy);
HttpURLConnection connection = NetCipher.getHttpURLConnection(sourceUrl);
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me.
HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
int respCode = con.getResponseCode();
if (respCode != HttpsURLConnection.HTTP_OK)
{
throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
else {
//read the content from server
}
1/ It is recommanded to use apache HttpClient rather than URLConnection (see http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html)
2/ for login and password, why not use Http Authentication ? both basic and digest are supported by android.
3/ as for you problem, you don't close the underlying outputStream.
you should do:
OutputStream os = con.getOutputStream();
DataOutputStream output = new DataOutputStream(os);
output.writeBytes(query);
output.close();
os.close();
Check Server service validity with other technology and/or classic java. You didn say in your question if you succeed to discriminate the server from the issue.
from java doc ...getResponseCode returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).
Java https post request example : http://www.java-samples.com/java/POST-toHTTPS-url-free-java-sample-program.htm
try to close your outputstream after querying the status and not before...that may help
Here is how you should send POST requests in Android
HttpPost httpGet = new HttpPost(server + "/login?email="+username+"&password="+password);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpGet);
You can read response using:
response.getEntity().getContent()
I have to connect to a webserver from android and I have to access a webservice and a webpage from the webserver. Can anybody help me? Please give step by step process with some code snippets because I am new to android and I don't know anything in connecting to a webserver.
You can use an HttpClient:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
HttpResponse httpResponse = httpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
// user reader to read & parse response
reader.close();
Parsing the response obviously depends on the format (e.g. SOAP, JSON, etc.)
You haven't given very much info (what kind of web page, XML/JSON/HTML/etc. ?). But the basic principles of regular Java apply. Using URL and InputStream:
URL url = new URL(...);
InputStream is = url.openStream();
And from there it depends what kind of data you're dealing with.
If you don't want to use an additional library, here is a means for sending an "id" and "name" to a server:
URL url = null;
try {
String registrationUrl = String.format("http://myserver/register?id=%s&name=%s", myId, URLEncoder.encode(myName,"UTF-8"));
url = new URL(registrationUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("MyApp", "Registration success");
} else {
Log.w("MyApp", "Registration failed for: " + registrationUrl);
}
} catch (Exception ex) {
ex.printStackTrace();
}
You could just as easily send other data via this URI "GET" style, but if you need to send something more detailed a POST will be required.
Note: Originally posted to answer a similar question here: How to connect android to server