HttpURLConnection connection timeout not working - android

I have set connection timeout and Read timeout but still they are getting ignored, the request just stays on forever. How do I set a timeout such that the request gets cancelled if the timeout is reached ?
This is my code snippet, appreciate your help.
urlConnection = (HttpURLConnection) saveURL.openConnection();
// is output buffer writer
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "text/html");
urlConnection.setRequestProperty("userid", id);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(jsonString);
writer.flush();
// json data
writer.close();
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
int responseCode = urlConnection.getResponseCode();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketTimeoutException soce) {
// TODO Auto-generated catch block
soce.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != urlConnection)
urlConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

I am not sure if this is the best option, what I did was to set a Timer which I used to do a disconnection on HttpURLConnection once time was up. It seems to work fine so far. If anyone can point out the disadvantages of this approach and suggest a better way, I would appreciate it.

Related

Authentication not working in Put method android

How to get response in put method with Authentication using four Headers.In ios it works fine but not in Android.
Authentication code is generated from the data HMAC-SHA256 with the secret key provided after validation as the key
HttpPut put = new HttpPut(xAuthurl);//url
Log.v("put", "" + put);
try {
put.setEntity(new StringEntity(data, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "UnsupportedEncoding: ", e1);
}
//Here are the four headers......
put.addHeader("Content-type", "application/json");
put.addHeader("x-Auth-user", Validation.id);//id of the profile
put.addHeader("X-Auth-Hash", hexBytes);// Hexadecimal value
put.addHeader("X-Auth-Time", sdf.format(datetime));//date format in utc
HttpResponse response = null;
try {
response = http.execute(put);
Log.v("response", "" + response.getAllHeaders());
} catch (ClientProtocolException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO
// Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "This is what we get back:"
+ response.getStatusLine().toString() + ", "
+ response.getEntity().toString());
try {
inputStream = response.getEntity().getContent();
} catch (IllegalStateException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO Auto-generated catch block
e1.printStackTrace();
}
if (inputStream != null) {
try {
result = convertInputStreamToString(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("result", "" + result);
} else {
result = "Did not work!";
}
return 1;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
result i get is {"Message":"An error has occurred."}

Android gcm sending link testing

Sir,,
I would like to try my application to test push-notification by typing this link below , but it comes to trying , there is no effect.Would you please tell me what is the correct format for the hyperlink to test my Application program ?
The below is my link
https://android.googleapis.com/gcm/send?registration_ids=
APA91bHhJQJGK1OJxYHcZeH81JoAprU97CAvMHQ58cHj3MYHD204MTn1W9Kl_i51UV8ej5qwLfkwvK-vihfuWjXG6iBvkUZJuclqoNbAjx_K2mN_P2ai4rI82P0dax_tm7NHc-k_1FsBn6hvwxjxxPdgMdtYpSIdwA
&data.message="hello testing"
collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "
You can actually test it from the Android device itself:
public class PushTester {
final static private String deviceId = "YOUR_DEVICE_ID";
final static private String apiId = "YOUR_API_ID";
final static private String sendUrl = "https://android.googleapis.com/gcm/send";
static void testPush() {
URL url;
HttpsURLConnection urlConnection;
OutputStream os = null;
InputStream is = null;;
try {
url = new URL(sendUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("User-Agent", "Android Push tester");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key="+apiId);
JSONObject message = new JSONObject();
JSONArray regIds = new JSONArray();
JSONObject data = new JSONObject();
regIds.put(deviceId);
message.put("registration_ids", regIds);
//message.put("collapse_key", value)
data.put("something", "value");
message.put("data", data);
urlConnection.setDoOutput(true);
os = urlConnection.getOutputStream();
os.write(message.toString().getBytes());
os.flush();
int status = urlConnection.getResponseCode();
is = urlConnection.getInputStream();
byte[] response = new byte[4096];
is.read(response);
String responseText = String.valueOf(response);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
os = null;
is = null;
}
}
}

HttpURLConnection works on emulator but not on the device

I'm trying to experiment the HttpURLConnection to get some XML from a server.
This is the code I'm using:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String myConn = this.getString(R.string.myConnection);
HttpURLConnection httpConnection = null;
InputStream in = null;
try {
URL mySite = new URL(myConn);
URLConnection connection = mySite.openConnection();
TextView tv = (TextView)this.findViewById(R.id.myTextView);
httpConnection = (HttpURLConnection)connection;
in = httpConnection.getInputStream();
String myString = convertStreamToString(in);
tv.setText(myString);
} catch (IOException ex) {} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
httpConnection.disconnect();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
On the emulator this code works and i can see the stream on the TextView...
On my device I can't see anything (3g connection)..
Did I miss something?
thanks
By using AsyncTask You can solve this problem.

How to separate my code to many method?

I am a new in android developing, I've code to connect to server and send commands,
How to separate connection code in method and sending code in another method.
my code as following:
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
// connect code
socket = new Socket("172.16.149.64", 8888);
// sending code
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Write a class of your own and make the Socket one of its member variables. You can then write connect() and sendData() methods to your class using the same socket in both methods.

android app connects to robot via ip address and port number

I need to code to connect between my android app and robot via ip address and port number using wifi connection.
I have part of code but I think that it need to commands to create connection.
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.10.5", 2525);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
You should call flush on your output stream after writing.
Also, close the streams before closing the socket in the finally block.
What is you problem exactly ?
Did you look at the logs on the server side to see if connection was established ?
Do you see that your server accepts the connection ?
Do you reecive any data on the server side ?
Regards,
Stéphane

Categories

Resources