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.
Related
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.
Not very easy to explain:
I have this app for streaming online radio. The problem was first with m3u format (which android somehow cannot normally stream like pls), so I have to parse the url with this ParserM3UToURL (that I found somewhere)... like this:
Uri u = Uri.parse(ParserM3UToURL.parse(STREAM_URL, sdkVersion, c));
player = MediaPlayer.create(c, u);
Mostly it works ok but it has one bug...
I'm testing this on two devices one old 2.2.2. (api level 17), other 4.3 (api level 23). Older device works fine. It can stream radio over wifi or mobile data, but the newer device has some problem with streaming over mobile data (on wifi it works ok). The application crashes because the parse function returns null: http://pastebin.com/ghbAqGzM
And I assume there are many more phones with 4.x than 2.x android. Which of course is very painful for me. Somehow I have to fix this.. So I really hope somebody will have some clue about this. I hope my explanation was not to confusing...
This is the ParserM3UToURL.parse() function:
public static String parse(String paramString, int sdkVersion, Context c)
{
try
{
StrictModeWrapper.init(c);
HttpURLConnection localHttpURLConnection = (HttpURLConnection)new URL(paramString).openConnection();
InputStream localInputStream = localHttpURLConnection.getInputStream();
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));
StringBuffer localStringBuffer = new StringBuffer();
while (true)
{
String str = localBufferedReader.readLine();
if (str == null)
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
break;
}
if (str.contains("http"))
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
return str;
}
localStringBuffer.append(str);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Below is what i worked on to stream radio (m3Urls). The example below uses a service. When the service is started, the url is parsed. Note that in the onPostExecute, parsed file is prepared. Once the file is prepared(completed buffering), the file is played/started and stopped upon completion.
public class BackgroundRadioService extends Service implements
OnCompletionListener, OnPreparedListener{
MediaPlayer mediaPlayer;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
parseM3uUrlAndPrepare("http://listen.radionomy.com/andalousse.m3u");
return START_STICKY;
}
private void parseM3uUrlAndPrepare(final String url){
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
HttpClient httpClient;
HttpGet getRequest;
HttpResponse httpResponse = null;
String filePath = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
httpClient = new DefaultHttpClient();
getRequest = new HttpGet(url);
}
#Override
protected String doInBackground(String... params) {
try {
httpResponse = httpClient.execute(getRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(httpResponse != null)
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
} else {
InputStream inputStream = null;
try {
inputStream = httpResponse.getEntity().getContent();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
//Log.v("PLAYLISTLINE", "ORIG: " + line);
if (line.startsWith("#")) { // Metadata
} else if (line.length() > 0) {
filePath = "";
if (line.startsWith("http://")) { // Assume it's a full URL
filePath = line;
} else { // Assume it's relative
try{
filePath = getRequest.getURI().resolve(line).toString();
}catch(IllegalArgumentException e){
}catch(Exception e){
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepareAsync(); //this will prepare file a.k.a buffering
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
asyn.execute("");
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
}//end of Service class declaration
Note: This ignores playlists hence assumes the m3u parsed will return only one file. Let me know if you would like to handle playlists so I modify my answer :)
I solved it thanks to this question's comments: POST request failing when in 3G
The problem was actually with proxies on 3G. So if proxies are disabled, no weird http requests.
I modified my code a little. Thanks to Nana's answer I no longer need a m3u parser. I also no longer use HttpClient but HttpURLConnection instead. So when calling URL.openConnection() I add the Proxy.NO_PROXY parameter to that function and bam!
So the solution is "use HttpURLConnection not HttpClient and add NO_PROXY parameter":
conn = (HttpURLConnection) the_url.openConnection( Proxy.NO_PROXY );
I need to load an image from http, and I'm using this code:
Bitmap bitmap;
InputStream is = null;
try {
is = (InputStream) new URL("www.TESTWEBSITE.com/TEST.JPG").getContent();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bitmap = BitmapFactory.decodeStream(is);
But bitmap is still null.. Any help please ?
Update : this is full snapshot performing what you want :
Bitmap bitmap = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL("www.TESTWEBSITE.com/TEST.JPG");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Please, make sure to run it off UI thread, such as in AsyncTask as others have commented. You can try it in main thread for experimental purposes but be prepared for ANR.
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;
}
}
}
I am developing an application to send a request to port 502 and want to read the response from the same port.
This is what i tried so far
public class Autoamtion extends Activity {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.v("on create", "on create");
final ToggleButton fanOn = (ToggleButton) findViewById(R.id.toggleButton1);
fanOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (fanOn.isChecked()) {
Toast.makeText(Autoamtion.this, "Fan is On",
Toast.LENGTH_SHORT).show();
Log.v("on create", "on create");
try {
echoSocket = new Socket("192.168.1.19", 502);
out = new PrintWriter(echoSocket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to:192.168.1.19");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stdIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
echoSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
Toast.makeText(Autoamtion.this, "Fan is Off",
Toast.LENGTH_SHORT).show();
}
});
}
}
i just installed one simulator which opens the port 502. i confirmed that port which gets open after running this simulator.
i just established the connection with 502 port. i am not getting any response from there.
Please guide me through this so i can make this working. Any advice and help would be appreciated .
Thanks
You should post stackTrace as well, to check what's failling.
At least one thing is not consistent in your information, your refer in the text port 503 and in your code you are using echoSocket = new Socket("192.168.1.19", 502); connecting to port 502.