I am trying to create android application using HttpURLConnection API. I successfully logging and now trying to fire another query say (http://someserver.com/myapp/getemployeebyid?userid.) On execution of this statement I am getting following exception.
java.net.protocolexception: connection already established
I have closed input stream.
My code is.
mymethod(urlString){
InputStream myis = null;
URL url = new URL(urlstring);
HttpURLConnection httpURLconnection = (HttpURLConnection)
url.openConnection();
httpURLconnection.setReadTimeout(10000);
httpURLconnection.setConnectTimeout(15000);
httpURLconnection.setRequestMethod("GET");
httpURLconnection.setDoInput(true);
httpURLconnection.connect();
int myresponse = httpURLconnection.getResponseCode();
if (myresponse == 200) {
ResponseFlag = true;
myis = httpURLconnection.getInputStream();
// Convert the InputStream into a string
contentAsString = convertIttostring(myis);
}
else {
ResponseFlag = false;
somemesg = "incorrect response ";
}
}
catch(Exception Ex){
System.out.println(Ex.toString());
somemesg="connection failed";
}
finally {
if (myis != null) {
myis.close();
}
}
}
Noow I have 2 queries.
Do i need to write connection.disconnect(); below myis.close(), seperately?
After login success I am trying to reconnect. Cant I connect once and fired the queries. Once all the operation is done close the connection?
Related
I am kind of new in android development and I am having a weird issue.
The following code is supposed to work:
URL url = new URL("http://127.0.0.1/test.html");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
System.out.println("code: "+code);
The problem is, after I do the connection.connect(); nothing happens, even if I add a textX.setText() after the connect, I am not able to do any action.
Any idea what might be the issue?
This is my whole method, all I am trying to do is get some text from the API, which says "OK" actually, but I am not able to make it work.
public void conn (View view)
{
TextView text2 = (TextView)findViewById(R.id.text2);
text2.setText("connecting...");
String output="";
//All working until here
URL url;
HttpURLConnection urlConnection = null;
try {
output="about to connect";
text2.setText(output);
url = new URL("http://127.0.0.1:4444/localweb/api/api.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream in = urlConnection.getInputStream();
text2.append("\nabout to get code");
int code = connection.getResponseCode();
text2.setText(Integer.toString(code));
//urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.connect();
//output=urlConnection.getResponseMessage();
//text2.setText(output);
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
output=output+current;
}
//text2.setText(output);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
There wasn't something 'wrong' with the http client code, the issue is that you cannot launch the httpurlclient from the parent thread as I was trying to do, it must be executed in the background through an AsyncTask, after moving all the httpurlconnection stuff into an additional async function now I am able to get all the web details I needed.
I need to set the Host header for a very specific request and this is not being taken into account.
I know this is a restricted header, but how is it possible to do it?
Here's what I'm trying.
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestProperty("Host", "test.com");
urlConnection.setRequestMethod("GET");
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, String.format("response code: %d", responseCode));
} catch (IOException e) {
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
If I'm not misunderstanding your question perhaps you can do something like this instead of trying to set the host header under your try statement:
URL url = new URL("http://www.test.com/");
The host header will take on the information from whichever URL you supply.
Source:
https://developer.android.com/reference/java/net/HttpURLConnection.html
I am trying to hit a web service. it is working fine with android 4.4 or android 5.X. but when i am trying to hit "http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID" using android 4.1.1 it always returning me 307 status code. but this url is working fine with android 4.4 or 5.x. i also tried to hit other url it is working fine on android 4.1.1.
so please tell me what is the problem
Log.i(TAG, url);
String response = null;
HttpURLConnection conn = null;
try {
URL webServiceUrl = new URL(url);
conn = (HttpURLConnection) webServiceUrl
.openConnection();
Log.i(TAG, "Connection open");
conn.setRequestMethod(GET);
conn.setConnectTimeout(CONNECTION_TIME_OUT);
conn.setRequestProperty(CONTENT_TYPE, contentType);
conn.setRequestProperty(ACCEPT_TYPE, acceptType);
conn.setDoInput(true);
conn.connect();
Log.i(TAG, "Connection Connected");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK && conn.getInputStream() != null) {
response = StreamUtility.convertStreamToString(conn.getInputStream());
conn.getInputStream().close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
Replace your URL address with http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID/ (pay attention to / at the end). The response code will be 200.
UPDATE:
With your current URL address (http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID) without / at the end, you can use the following code:
String address = "http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID";
URL url = new URL(address);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false);
// if print out (debug or logging), you will see secondURL has / at the end
URL secondURL = new URL(urlConnection.getHeaderField("Location"));
HttpURLConnection urlConnection1 = (HttpURLConnection) secondURL.openConnection();
Then use urlConnection1.getResponseCode()
Hope it helps!
BNK's answer helped, I fixed it like this so that it also works on newer devices (location header was returned as null / empty!)
String headerLocation = httpsUrlConnection.getHeaderField("Location");
logger.debug("Location header: " + headerLocation);
// if the redirect URL ends with a "/" sign, but the original URL does not, it's probably the redirect bug
String originalURL = url.toString();
if (!TextUtils.isEmpty(headerLocation) && headerLocation.endsWith("/") && !originalURL.endsWith("/"))
{
logger.info("Redirect Location differs from original URL, create new connection to: " + headerLocation);
httpsUrlConnection = (HttpsURLConnection) new URL(headerLocation).openConnection();
// optional
httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
}
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 .
In my android app, I am trying to pull data from server by doing a POST request.
I'm using HttpURLConnection class to make the requests as Apache's HttpClient is no longer maintained by android.
Here's what I'm doing.
private boolean callWS() {
try {
// To avoid the bug in httpurlconnection prior froyo which
// causes the getInputStream to return headers along with response
if (Build.VERSION.SDK_INT < 8)
System.setProperty("http.keepAlive", "false");
mHttpResponseCode = 0;
mErrorMessage = "";
// Initialize connection
URL connectURL = new URL(mServerUrl);
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setReadTimeout(30000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
// Set some headers
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Encoding", "deflate, gzip");
connection.setRequestProperty("Content-Length", mParameters.length() + "");
// Connect to host
conn.connect();
// Write parameters to connection
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(mParameters);
writer.flush();
writer.close();
// Wait for http response code
mHttpResponseCode = conn.getResponseCode();
// Read response from connection
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1)
break;
baf.append(buffer, 0, read);
}
// Decompress gzipped response
if (conn.getHeaderField("Content-Encoding") != null && conn.getHeaderField("Content-Encoding").contains("gzip"))
mResponseString = decompress(baf.toByteArray());
else
mResponseString = new String(baf.toByteArray());
mResponse.setResponse(mResponseString);
isWSCallSuccessfull = true;
} catch(UnknownHostException unknownHostException) {
isWSCallSuccessfull = false;
mErrorMessage = "Unknown host exception";
unknownHostException.printStackTrace();
mLogger.putStacktrace(unknownHostException);
} catch(SocketException socketException) {
isWSCallSuccessfull = false;
mErrorMessage = "Socket Exception";
socketException.printStackTrace();
mLogger.putStacktrace(socketException);
} catch(SocketTimeoutException socketTimeOutException) {
isWSCallSuccessfull = false;
mErrorMessage = "Socket Timeout Exception";
socketTimeOutException.printStackTrace();
mLogger.putStacktrace(socketTimeOutException);
} catch(SSLException sslException) {
isWSCallSuccessfull = false;
mErrorMessage = "SSL Exception";
sslException.printStackTrace();
mLogger.putStacktrace(sslException);
} catch(IOException ioException) {
isWSCallSuccessfull = false;
mErrorMessage = "IO Exception " + ioException.getMessage();
ioException.printStackTrace();
mLogger.putStacktrace(ioException);
}
mResponse.setHttpResponseCode(mHttpResponseCode);
mResponse.setErrorMessage(mErrorMessage);
mResponse.isWSCallSuccessful(isWSCallSuccessfull);
return isWSCallSuccessfull;
}
This works fine on every device except devices running 2.2 (did not try it on 2.1).
In 2.2, it works fine. But if I leave this part of code idle for more than 30s, it returns me with -1 as http response code the very next time.
Another thing to note is that this happens only with HTTPS urls and not with HTTP Urls. I do not want to use HttpsURLConnection class because at times I may want to use http as well.
I'm not closing the connection just to keep the connection alive. What am I doing wrong?
If you want to use Https and Http at the same time and does not want to create a seperate connection -and if HttpsUrlConnection solves your "-1 issue" you can use the following approach:
URLConnection conn = new URL(url).openConnection();
if (conn instanceof HttpsURLConnection) {
// do stuff with cast to HttpsUrlConection
}
else {
// do stuff with cast to HttpUrlConnection
}
I took this answer as a reference