The docs say AsyncTask is designed to handle short operations(few seconds maximum) and states that Java classes like FutureTask are better for operations that last long. So I tried to send my location updates to the server using FutureTask but I am getting NetworkOnMainThreadException. I don't want to use AsyncTask because I wanted to keep the http connection open until the updates are cancelled. Here is my code:
SendLocation updates = new SendLocation(idt, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
FutureTask ft = new FutureTask<String>(updates);
boolean b = ft.cancel(false);
ft.run();
class SendLocation implements Callable<String> {
String t, la, lo;
public SendLocation(String a, String b, String c){
this.t = a;
this.la = b;
this.lo = c;
}
public String call() {
sendUpdates(token, la, lo);
return "Task Done";
}
public void sendUpdates(String a, String b, String c){
HttpURLConnection urlConn = null;
try {
try {
URL url;
//HttpURLConnection urlConn;
url = new URL(remote + "driver.php");
urlConn = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", "true");
//urlConn.setDoInput(true); //this is for get request
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
try {
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("drt", a);
json.put("drlat", b);
json.put("drlon", c);
String postData = json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.flush();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg = "";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line;
}
Log.i("msg=", "" + msg);
} catch (JSONException jsonex) {
jsonex.printStackTrace();
Log.e("jsnExce", jsonex.toString());
}
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex) {
ioex.printStackTrace();
try { //if there is IOException clean the connection and clear it for reuse(works if the stream is not too long)
int respCode = urlConn.getResponseCode();
InputStream es = urlConn.getErrorStream();
byte[] buffer = null;
int ret = 0;
// read the response body
while ((ret = es.read(buffer)) > 0) {
Log.e("streamingError", String.valueOf(respCode) + String.valueOf(ret));
}
// close the errorstream
es.close();
} catch(IOException ex) {
// deal with the exception
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code " + String.valueOf(e));
}
}
}
Doesn't it get executed in a worker thread? If the answer is no why does the docs say that it is an alternative to AsyncTask?
Your code must not be in the void run() method. This is where the asynchronous code is ran.
Related
I'm using Asynctask to pass the parameters of API. The Asynctask executing but the String Response in Asynctask PostExecute giving me a null for a device with SDK 23 and below. But when the device is equal or higher to SDK24(Nougat), it works perfectly and the data are being sent to the API however when the SDK is 23 and lower data are not being sent to API. Does anyone encounter this problem? Please enlighten me what I miss in my code or I do wrong code. Massive thank you.
private class sendToServerOfficial extends AsyncTask<String,Void,String> {
int statusCodeone;
String convert_txt_et_username = et_username.getText().toString();
String convert_txt_content = et_content.getText().toString();
#Override
protected String doInBackground(String... strings) {
try {
urlURL = new URL("http://www.testingsite.com/api/sendServer?/ip="+getIPAddress+"&phone_num="+getMobilePhoneNumber+"&user_text="+convert_txt_et_username+"&content_text="+convert_txt_content);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlURL.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","UTF-8");
httpURLConnection.connect();
statusCodeone = httpURLConnection.getResponseCode();
if (statusCodeone == 200) {
InputStream it = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
buff.close();
read.close();
return dta.toString();
}
}
catch (ProtocolException e) { e.printStackTrace(); }
catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return null;
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(MainActivity.this, response + "Form is submitted already" + urlURL, Toast.LENGTH_LONG).show();
txt_inputURL.setEnabled(true);
btnClick.setClickable(true);
txt_inputURL.getText().clear();
}
}
all of a sudden my mobile device can't connect to the local server anymore. async tasks are not executed and i just can't figure out why. slowly i'm getting really desperate because in my opinion i didn't change anything to cause this.
as an example, this is a background task which is not working
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
android {
useLibrary 'org.apache.http.legacy'
}
HttpClient won't import in Android Studio
You should think about using a HTTP library, there is a bunch of them on internet, some are really easy to use, optimize and errorless.
For example, Volley (made by Google, I really like this one), okHttp or Picasso (for image).
You should take a look at this.
If you want to send (output), for example with POST or PUT requests you need to use this :-
urlConnection.setDoOutput(true);
In your code :-
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true); // HERE
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
I am getting following error in con.getResponseCode()
java.net.SocketTimeoutException: failed to connect to example.com (port 80) after 3000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:223)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:475)
at java.net.Socket.connect(Socket.java:861)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:152)
at com.android.okhttp.Connection.connect(Connection.java:101)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
First time when it gets called it works perfectly.
But it stops working after it and it may start working randomly after some time.
public class HTTPLoader {
public static String loadContentFromURLGET(String urlString,List<String[]> getVars,Context context){
int retry = 0;
HttpURLConnection con=null;
BufferedReader in = null;
StringBuffer response=null;
if (!isConnectingToInternet(context)){
return "{'error':'No Internet connection!'}";
}
while (retry++<=RETRY_CNT) {
try {
String urlParameters = "";
for (String[] var : getVars) {
urlParameters += var[0] + "=" + URLEncoder.encode(var[1], "UTF-8") + "&";
}
if (urlParameters.length() > 1) {
urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
}
if (urlString.charAt(urlString.length() - 1) != '?') {
urlString += "&";
}
URL url = new URL(urlString + urlParameters);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(3000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoInput(true);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
retry = RETRY_CNT+1;
break;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con!=null) {
con.disconnect();
}
in = null;
con = null;
}
}
if (response!=null)
return new String(response);
return "{'error':'No Internet connection!'}";
}
}
This loadContentFromURLGET is getting called from IntentService
public class ChatUtil extends IntentService{
protected String loadAllChats(String date){
String response = "";
try {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = sharedPreferences.getString(QuickstartPreferences.EMAIL, "");
List<String[]> postVars = new ArrayList<>();
postVars.add(new String[]{"getconversation", "yes"});
postVars.add(new String[]{"user_id", email});
postVars.add(new String[]{"last_date", date});
String urlString = getString(R.string.get_conversation_url);
response = HTTPLoader.loadContentFromURLGET(urlString, postVars,getApplicationContext());
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("error")) {
//Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
return jsonObject.getString("error");
}
}catch (JSONException e) {
}
}
protected void onHandleIntent(Intent intent) {
String task = intent.getStringExtra(QuickstartPreferences.CURRENT_TASK);
Intent nintent;
String date = "";
String[] arr3 = new NewsDBUtil(getApplicationContext()).getLastChatEntry(null);
if (arr3!=null)
date = arr3[1];
loadAllChats(date);
nintent = new Intent(QuickstartPreferences.LOADING_ALL_CHAT);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(nintent);
}
}
Tried closing and disconnecting stream in finally block.
But no Success.
you can put con.getResponseCode(); between try ...catch block if it throw SocketTimeoutException Exception make another try , but make sure you extend your timeout
if (responseCode != 200) {
....
...
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
}
may this help
Without specific ContentLength via setFixedLengthStreamingMode
I found some devices generated incomplete http request
cause the server has to wait until either server or client timed out
you can use wireshark to analyze the problem
I have built a chat application in Android powered by sockets. The messages send and receive fine, so long as the user does not send messages with special characters, ie. Hey, it's me, will not work, but Hey its me, will, the comma and apostrophe prevent the message from being delivered.
I attempted using URLEncoder, but that did not allow the unique characters to be sent.
Sending message method:
public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8")
+ "&message=" + URLEncoder.encode(message, "UTF-8")
+ "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
+ "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
+ "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
+ "&gcmregid=" + gcmRegistrationID
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
with
SocketerInterface socketOperator = new Socketer(this);
and Socketer class as:
public class Socketer implements SocketerInterface {
// Have to set the proper ports that apache is runnign on as well as your
// computers IP address: ie. ip:4430 or 800
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
// + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/"; // Google Compute Engine Access
//+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access
+ ipAddress.getFeastChatServer(); // For Heroku access
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new
// PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.v("XML MESSAGE", inputLine);
if (inputLine.equals("exit") == false) {// as long as have
// noted exited yet,
// will continuing
// reading in
Log.v("XML MESSAGE", inputLine);
// appManager.messageReceived(inputLine);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket
.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ", "");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params) {
URL url;
String result = new String();
try {
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
// Testing to remove <head/> tag from Google App Engine
//return result.replace("<head/>","");
return result;
}
public int startListening(int portNo) {
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
// e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
// e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket",
"Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening() {
this.listening = false;
}
public void exit() {
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
.hasNext();) {
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}
How can I format/encode to allow sending these messages?
Java uses UTF-16 for internal String representation, but it looks like you are using UTF-8, but you aren't doing anything special to convert it from UTF-8 when reading it from BufferedReader. In the params, try specifying UTF-16 instead.
From the Java String documentation:
A String represents a string in the UTF-16 format
I was previously using HttpClient and BasicNameValuePairs, for some reason i have to shift to HttpUrlConnection.
Hence this code, to make a HttpPost request with certain parameters:
public class MConnections {
static String BaseURL = "http://www.xxxxxxxxx.com";
static String charset = "UTF-8";
private static String result;
private static StringBuilder sb;
private static List<String> cookies = new ArrayList<String>();
public static String PostData(String url, String sa[][]) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(BaseURL + url)
.openConnection();
} catch (MalformedURLException e1) {
} catch (IOException e1) {
}
cookies = connection.getHeaderFields().get("Set-Cookie");
try{
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
}catch (Exception e) {
//Here i get Exception that "java.lang.IllegalStateException: Already connected"
}
OutputStream output = null;
String query = "";
int n = sa.length;
for (int i = 0; i < n; i++) {
try {
query = query + sa[i][0] + "="
+ URLEncoder.encode(sa[i][1], "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (Exception e) {
//Here i get Exception that "android: java.net.protocolException: Does not support output"
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
}
}
InputStream response = null;
try {
response = connection.getInputStream();
} catch (IOException e) {
//Here i get Exception that "java.io.IOException: BufferedInputStream is closed"
} finally {
//But i am closing it here
connection.disconnect();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
response, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append("\n" + line);
}
response.close();
result = sb.toString();
} catch (Exception e) {
}
return result;
}
}
But i get such Exceptions as commented in the code.
Actually i am calling MConnections.PostData() twice from my Activity using a AsyncTask. This might cause the Exception: Already Connected but i am using connection.disconnect. But why am i still getting that Exception?
Am i using it the wrong way?
Thank You
For the protocol exception, try adding the following before you call getOutputStream():
connection.setDoOutput(true);
Discovered this answer thanks to Brian Roach's answer here: https://stackoverflow.com/a/14026377/387781
Side note: I was having this issue on my HTC Thunderbolt running Gingerbread, but not on my Nexus 4 running Jelly Bean.