I'm trying to serve a small file on my desktop using NanoHTTPD. The server starts fine but due to some unknown reason, it is unable to serve files. The same program works fine in Android. Can anyone give me some pointers? It's being more than an hour but I've got no clue. Here is my desktop version of NanoHTTPD server:
package com.desktopserver;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Map;
import com.desktopserver.NanoHTTPD.Response.Status;
public class MainClass {
static int PORT = 8080;
static WebServer MyServer;
static FileInputStream fis;
static BufferedInputStream bis;
public static void main(String[] args) {
MyServer = new WebServer();
try {
MyServer.start();
System.out.println("Webserver Started # PORT:8080");
} catch (IOException e) {
e.printStackTrace();
}
}
public static class WebServer extends NanoHTTPD {
String MIME_TYPE;
public WebServer() {
super(PORT);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
try {
File file=new File("/home/evinish/Music/Meant_to_live.mp3");
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
MIME_TYPE= URLConnection.guessContentTypeFromName(file.getName());
System.out.println("\nMIME TYPE: "+MIME_TYPE);
System.out.println("\nFILE NAME: "+file.getName());
} catch (IOException ioe) {
System.out.println("File IO Exception");
}
return new NanoHTTPD.Response(Status.OK, MIME_TYPE, bis);
}
}
}
I do get this output, but that's it:
Webserver Started # PORT:8080
What am I missing here? Thanks a lot for your help.
Because you don't use "ServerRunner" class. ServerRunner hold you server to until any key press.
But in real application this don't work you want some change in NanoHTTPd file
line no 196 to
myThread.setDaemon(false);
Related
I'm a newbie in Android Development. I want to get metadata from Shoutcast Server, and found streamscraper to be the easiest one to use. But my problem is, I don't know how to use it. The homepage itself only showing something like in how to use it:
import java.net.URI;
import java.util.List;
import net.moraleboost.streamscraper.Stream;
import net.moraleboost.streamscraper.Scraper;
import net.moraleboost.streamscraper.scraper.IceCastScraper;
public class Harvester {
public static void main(String[] args) throws Exception {
Scraper scraper = new IceCastScraper();
List streams = scraper.scrape(new URI("http://host:port/"));
for (Stream stream: streams) {
System.out.println("Song Title: " + stream.getCurrentSong());
System.out.println("URI: " + stream.getUri());
}
}
}
Searched anywhere and found no project sample of how to use this. I hope one of you can post the code of how to use it, or make a tutorial for it.
No need to use external libraries. The following pages give you:
Current song: http://yourstream:port/currentsong?sid=#
Last 20 songs: http://yourstream:port/played.html?sid#
Next songs: http://yourstream:port/nextsongs?sid=#
An Android java class which prints the current song:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class NowPlaying {
public void CurrentSong() {
try
{
URL url = new URL("http://www.mofosounds.com:8000/currentsong?sid=#");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
Note: the nextsongs?sid=#feature must be supported by the player of the stream.
I have an odd problem; if I run this code I get a java.io.FileNotFoundException: https://graph.facebook.com/debug_token?input_token=1234&access_token=1234. This only occurs when I call client.getInputStream() inside my AsyncTask. Click the link: it clearly works.
Let's call this case 1.
Now, when I run the exact same code outside of my AsyncTask, I get a NetworkOnMainThreadException, but client.getInputStream() works...
Consider this case 2.
I know why I get the NetworkOnMainThreadException in case 2, but I don't understand why the FileNotFoundException only happens in case 1, and not in case 2. The code is identical! I've been looking at this for hours and I just don't know what I am doing wrong.
EDIT: apperently the FileNotFoundException occurs because of an error response code. I figured this out by getting the error stream with .getErrorStream() when the exception occurs.
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
public class Temp {
private String getResponse(InputStream stream){
Scanner s = new Scanner(stream).useDelimiter("\\A");
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
public void run(String url){
URL uri;
HttpsURLConnection client = null;
try {
uri = new URL(url);
client = (HttpsURLConnection) uri.openConnection();
client.setReadTimeout(15*1000);
} catch (IOException e) {
e.printStackTrace();
}
new RetrieveStream().execute(client);
}
private class RetrieveStream extends AsyncTask<HttpsURLConnection, Void, String> {
private String returnString = null; //don't change this!
HttpsURLConnection client;
#Override
protected String doInBackground(HttpsURLConnection... client) {
try {
this.client = client[0];
InputStream stream = this.client.getInputStream();
Log.d(getClass().getSimpleName(), "response: "+getResponse(this.client.getInputStream()));
} catch (FileNotFoundException e) {
Log.d(getClass().getSimpleName(), "error output: "+getResponse(this.client.getErrorStream()));
e.printStackTrace();
} catch (IOException e) {
Log.d(getClass().getSimpleName(), "error: "+getResponse(this.client.getErrorStream()));
e.printStackTrace();
}
this.client.disconnect();
return returnString;
}
protected void onPostExecute(String output) {
Log.d(getClass().getSimpleName(), "output: "+output);
}
}
}
i am not deep into android development, but since the Thread seem to be aware of connections (implied by "NetworkOnMainThreadException"), i'd suggest to handover the URL instance to your AsyncTask and open the connection there, instead of hand over the client.
Apart from this, by reading the api, i'd expect a
client.connect();
before
client.getInputStream();
get's called.
References:
https://developer.android.com/reference/java/net/URL.html#openConnection()
https://developer.android.com/reference/java/net/URLConnection.html#getInputStream()
It's not very clear why the FileNotFoundException occurs, but I was able to get the response with .getErrorStream() instead of .getInputStream(). My question is edited accordingly. Please ignore the other answers, they provide no solutions.
I have a class developed in eclipse (on the same computer ) and I am trying to bring it over to Android Studio. Android Studio gives me an error, it cannot resolve symbol HttpsURLConnection
On Oracle's website and it is said the class is in java.net.URLConnection, when I import it the line is greyed saying it was already imported.
code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
public class cBitTrex {
static int test;
/////////////////////////////////////////////////////////////////////
// Run code to talk to server on a thread
// Every onunce in a while code to tal to server will freex
// WEcall thread methed run and then wait for thread to exit with a time out
public class cThread extends Thread{
String reply=null;
String url;
public void run()
{
String ireply;
error="";
ireply="";
try {
ireply="";
URL myurl = new URL(url);
System.out.println("Open thread connection");
// This is where the error is
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setConnectTimeout(15000);
System.out.println("Get input thread stream");
InputStream ins = con.getInputStream();
System.out.println("Create reader");
InputStreamReader isr = new InputStreamReader(ins);
System.out.println("Creat buffer threadreader");
BufferedReader in = new BufferedReader(isr);
String inputLine;
System.out.println("THREAD Read indata2");
int t;
while ((t= in.read()) != -1)
{
ireply+=(char)t;;
}
System.out.println("finish Read indata");
} catch (Exception e)
{
error=new String(e.getMessage());
System.out.println("Exception in getting data from API server");
reply=null;
}
// Set return valur at end of thread so if thread call tiimout we will not
// get any data
reply=ireply;
}
};
..
...
}
This class you are searching for does not exist, at least in Android. The one that is provided by the Android SDK is java.net.HttpURLConnection. By the way, something you really have to take into account is programming for Android is not just like normal Java, it has some special rules. The correct documentation to search at is the one located in the Android SDK official Page.
Beside that, your error can be that you were importing in Eclipse a Library that you are not using anymore in Android Studio.
This question already has answers here:
How do I obtain crash-data from my Android application?
(30 answers)
Closed 5 months ago.
I'm currently developing an android app. I noticed a very rare error which leeds to a crash of my app. Unfortunately, I had my smartphone never connected to my pc when it occured. So, is there a way to automatically save all logs (and especially the thrown runtimeexceptions) to a file when my app starts, so that I can copy this file to my pc and analyse the error? The file should be overwritten on every start of my app, so that it contains only the logs of the last run... How can I achieve that?
regards
You can find help by following this link Writing crash reports into device sd card
You don't need to add external library.
import com.wordpress.doandroid.Training.R;
import android.app.Activity;
import android.os.Bundle;
public class CaptureExceptionActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets the default uncaught exception handler. This handler is invoked
// in case any Thread dies due to an unhandled exception.
Thread.setDefaultUncaughtExceptionHandler(new CustomizedExceptionHandler(
"/mnt/sdcard/"));
String nullString = null;
System.out.println(nullString.toString());
setContentView(R.layout.main);
}
}
And the Handler implementation
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Environment;
import android.util.Log;
public class CustomizedExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
private String localPath;
public CustomizedExceptionHandler(String localPath) {
this.localPath = localPath;
//Getting the the default exception handler
//that's executed when uncaught exception terminates a thread
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void uncaughtException(Thread t, Throwable e) {
//Write a printable representation of this Throwable
//The StringWriter gives the lock used to synchronize access to this writer.
final Writer stringBuffSync = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringBuffSync);
e.printStackTrace(printWriter);
String stacktrace = stringBuffSync.toString();
printWriter.close();
if (localPath != null) {
writeToFile(stacktrace);
}
//Used only to prevent from any code getting executed.
// Not needed in this example
defaultUEH.uncaughtException(t, e);
}
private void writeToFile(String currentStacktrace) {
try {
//Gets the Android external storage directory & Create new folder Crash_Reports
File dir = new File(Environment.getExternalStorageDirectory(),
"Crash_Reports");
if (!dir.exists()) {
dir.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
String filename = dateFormat.format(date) + ".STACKTRACE";
// Write the file into the folder
File reportFile = new File(dir, filename);
FileWriter fileWriter = new FileWriter(reportFile);
fileWriter.append(currentStacktrace);
fileWriter.flush();
fileWriter.close();
} catch (Exception e) {
Log.e("ExceptionHandler", e.getMessage());
}
}
}
Don't forget to add this permission in the manifest WRITE_EXTERNAL_STORAGE
I want to transfer messages from the android device to desktop application. My question is that can i connect the android WiFi device with the desktop WiFi device without any use of internet connection. I want to use it just like the Bluetooth. is this possible or not? if it is possible then how can i implement it?
Thanks and Regards
Amit Thaper
Here is an implementation of mreichelt's suggestion. i looked this up when i had the same problem and figured i'd just post my implementation of the solution. it's really simple. i also built a java server that listens for incoming requests from the android device (for debugging purposes mostly). here's the code to send stuff over the wireless:
import java.net.*;
import java.io.*;
import java.util.*;
import android.app.Activity;
import android.content.Context;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
public class SMSConnection {
/* The socket to the server */
private Socket connection;
/* Streams for reading and writing the socket */
private BufferedReader fromServer;
private DataOutputStream toServer;
/* application context */
Context mCtx;
private static final String CRLF = "\r\n";
/* Create an SMSConnection object. Create the socket and the
associated streams. Initialize SMS connection. */
public SMSConnection(Context ctx) throws IOException {
mCtx=ctx;
this.open();
/* may anticipate problems with readers being initialized before connection is opened? */
fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
toServer = new DataOutputStream(connection.getOutputStream());
}
public boolean open(String host, int port) {
try {
connection = new Socket(host, port);
return true;
} catch(IOException e) {
Log.v("smswifi", "cannot open connection: " + e.toString());
}
return false;
}
/* Close the connection. */
public void close() {
try {
connection.close();
} catch (IOException e) {
Log.v("smswifi","Unable to close connection: " + e.toString());
}
}
/* Send an SMS command to the server. Check that the reply code
is what is is supposed to be according to RFC 821. */
public void sendCommand(String command) throws IOException {
/* Write command to server. */
this.toServer.writeBytes(command+this.CRLF);
/* read reply */
String reply = this.fromServer.readLine();
}
}
that's a basic skeleton for a connection class. you simply instantiate the class, and call open on the instance you create with the host and port (don't forget to close the connection when you're done) and you can change the body of sendCommand to your liking. i've included a read/write operation in the function body as an example.
here is the code to run a server on a remote machine that listens for connections and spawns a thread to handle each request. it can easily interact with the above code for debugging (or any use).
import java.io.*;
import java.net.*;
import java.util.*;
public final class smsd {
///////MEMBER VARIABLES
ServerSocket server=null;
Socket client=null;
///////MEMBER FUNCTIONS
public boolean createSocket(int port) {
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port "+port);
System.exit(-1);
}
return true;
}
public boolean listenSocket(){
try{
client = server.accept();
} catch (IOException e) {
System.out.println("Accept failed: ");
System.exit(-1);
}
return true;
}
public static void main(String argv[]) throws Exception {
//
smsd mySock=new smsd();
//establish the listen socket
mySock.createSocket(3005);
while(true) {
if(mySock.listenSocket()) {
//make new thread
// Construct an object to process the SMS request message.
SMSRequest request = new SMSRequest(mySock.client);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
}
}
//process SMS service requests in an infinite loop
}
///////////end class smsd/////////
}
final class SMSRequest implements Runnable {
//
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public SMSRequest(Socket socket) throws Exception
{
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
public void run()
{
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
private void processRequest() throws Exception
{
// Get a reference to the socket's input and output streams.
InputStream is = this.socket.getInputStream();
DataOutputStream os = new DataOutputStream(this.socket.getOutputStream());
// Set up input stream filters.
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// Get the request line of the SMS request message.
String requestLine = br.readLine();
//print message to screen
System.out.println(requestLine);
//send a reply
os.writeBytes("200");
// Close streams and socket.
os.close();
br.close();
socket.close();
}
}
nb4namingconventions.
almost forgot. you will need to set these permissions inside the tags in your AndroidManifest.xml in order to use wireless.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
This is easily possible if both devices are using the same wifi network and can ping each other. You may just create a Java application on your desktop which creates a ServerSocket. Then you can open a Socket in your Android app using the desktop's IP address and send data through the OutputStream.
I believe that Amit is referring to having the machines connect directly to each other using wireless.
There is the development currently of the Wifi-direct specification to allow for Plug-in-Play setup of Access Points. The issue currently is ensuring one of the machines is an AP that other machine(s) can establish connection to.
I'm interested in how this relates to Ad-Hoc networks. I don't have a solution, however I am quite interested in this question too ! (Assuming this is your question Amit).