Android Httpurlconnection issue - nothing happens after .connect - android

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.

Related

HttpUrlConnect set Host header

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

HttpConnectionUrl always return status code 307

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);
}

HTTP url connection Android

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 .

http re connection in android

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?

inoutstream from a website displays nothing

i used the following code to read line by line from a website using textview. But the problem is the textview displays nothing.
I would like to know where my mistake is or how to correct my code to read data from a website.
To Note: i use the emulator.
JAVA Code:
try {
URL url = new URL("http://www.google.com");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.connect();
//readStream(con.getInputStream());
reader = new BufferedReader(new InputStreamReader (con.getInputStream()));
String line="";
while ( (line=reader.readLine()) != null)
tv00.setText(line);
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources