• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Http Connection Error - Already Connected ? No it isn't!

ac4android

Well-Known Member
Nov 3, 2015
198
29
Hi, I am re-using some http connection code, they worked well in my AsyncTask, tested and true.

This time, I called the method inside my Handler, like this:
Code:
  final Handler handler = new Handler();
  handler.post(new Runnable() {
  @Override
  public void run() {
  //TODO
  String slat = String.valueOf(dd);
  sysmsgview.setText(slat);
  latitudeview.setText(latitude);
  longitudeview.setText(longitude);
  accuracyview.setText(accuracy);
  if (running) {
  dd++;
  // hardvoded for testing
  latitude = "84.012345";
  longitude = "-114.2345";
  if (latitude != null && longitude != null){
  Toast.makeText(getApplicationContext(),
  "Uploading "+ dd + " Latitude:Longitude ->" + latitude +":" + longitude,
Toast.LENGTH_LONG).show();


  new UploadActivity(getApplicationContext()).execute( latitude, longitude);
  }
  }
  handler.postDelayed(this, 10000);
  }
  });
  }

It threw a java.lang.illegalStateException: Already connected.
How could it be already connected?????? Doesn't make sense.

Code:
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  if (!(conn instanceof HttpURLConnection)) {
  throw new IOException("ERROR: urlConn not instance of HttpUrlConnection.");
  }
  conn.setRequestMethod("POST");
  conn.connect();
  conn.setDoOutput(true);
  OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); // <-- THROWS EXCEPTION HERE!
  writer.write(data);
  writer.flush();
  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  StringBuilder stringBuilder = new StringBuilder();
  String line = null;
  // Read Server Response
  while ((line = reader.readLine()) != null) {
  stringBuilder.append(line);
  break;
  }
  reader.close();
  return stringBuilder.toString();
  } catch (Exception e) {
  return new String("Exception: " + e.getMessage());
  }

httpError.JPG


httpError222.JPG

httpError333.JPG
 
Hi and thx again.

Yeah, That's what I am going to do tomorrow, but Java is supposed to close the connection when it hits reader.close(), it never got to that point.

Still curious how the connection was in an "open" state because nothing in the code opens the connection prior to that point, unless the handler-thread and the AsyncTask were still alive after completing the last AsyncTask task.

I thought after an AsyncTask completes it job, it dies and releases memory, and not hang around like a background thread
 
Last edited:
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones