我想在Android中创建一个HTTP服务器。我想在这个程序中使用com.sun.net.httpserver。在你看来,这个包可以在Android程序中使用吗?我写了一个服务来做这件事。我的程序是休闲式的:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class HSMainService extends Service {
//region constants
public static final int MY_NOTIFICATION_ID = 1;
public static final int SERVERPORT = 8080;
//endregion
//************************
//region instance variables
private String TAG;
private Uri soundURI = Uri
.parse("android.resource://com.ebcompany.hs4/"
+ R.raw.alarm_rooster);
private long[] mVibratePattern = { 0, 200, 200, 300 };
private HttpServer server;
//endregion
//************************
//region constructors
public HSMainService() {
//TAG = getApplicationContext().getString(R.string.log_message_tag);
}
//endregion
//************************
//region override methods
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
//handleCommand(intent);
Log.i(TAG, "onStart");
Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
Log.i(TAG, "onStartCommand");
//Intent in = new Intent(getApplicationContext(), TestActivity.class);
//in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(in);
//Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Context cntx = getApplicationContext();
TAG = cntx.getString(R.string.log_message_tag);
Log.i(TAG, "Service creating");
final Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext())
.setContentInfo("HS4")
.setSmallIcon(R.drawable.icon)
.setContentTitle(cntx.getString(R.string.notification_content_title))
.setContentText(cntx.getString(R.string.notification_content_text))
.setTicker(cntx.getString(R.string.notification_tiker_text))
.setSound(soundURI)
.setOngoing(true)
.setLargeIcon((((BitmapDrawable) this.getResources().getDrawable(R.drawable.fire_eye_alien)).getBitmap()));
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder.setWhen(System.currentTimeMillis());
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
try {
server = HttpServer.create(new InetSocketAddress(SERVERPORT), 0);
server.createContext("IS2", new IS2Handler());
server.createContext("DSP", new DSPHandler());
server.setExecutor(Executors.newFixedThreadPool(0x5) ); // creates a default executor
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
//server.stop(0x1);
}
//endregion
//************************
}当我运行这个程序时,我得到这个错误:
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 I/dalvikvm﹕ Could not find method sun.misc.Service.providers, referenced from method com.sun.net.httpserver.spi.HttpServerProvider.loadProviderAsService
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 W/dalvikvm﹕ VFY: unable to resolve static method 421: Lsun/misc/Service;.providers (Ljava/lang/Class;Ljava/lang/ClassLoader;)Ljava/util/Iterator;
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 E/dalvikvm﹕ Could not find class 'sun.misc.ServiceConfigurationError', referenced from method com.sun.net.httpserver.spi.HttpServerProvider.loadProviderFromProperty
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 W/dalvikvm﹕ VFY: unable to resolve new-instance 155 (Lsun/misc/ServiceConfigurationError;) in Lcom/sun/net/httpserver/spi/HttpServerProvider;
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 E/dalvikvm﹕ Could not find class 'sun.misc.ServiceConfigurationError', referenced from method com.sun.net.httpserver.spi.HttpServerProvider.loadProviderFromProperty
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 W/dalvikvm﹕ VFY: unable to resolve new-instance 155 (Lsun/misc/ServiceConfigurationError;) in Lcom/sun/net/httpserver/spi/HttpServerProvider;
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 E/dalvikvm﹕ Could not find class 'sun.misc.ServiceConfigurationError', referenced from method com.sun.net.httpserver.spi.HttpServerProvider.loadProviderFromProperty
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 W/dalvikvm﹕ VFY: unable to resolve new-instance 155 (Lsun/misc/ServiceConfigurationError;) in Lcom/sun/net/httpserver/spi/HttpServerProvider;
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 E/dalvikvm﹕ Could not find class 'sun.misc.ServiceConfigurationError', referenced from method com.sun.net.httpserver.spi.HttpServerProvider.loadProviderFromProperty
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 W/dalvikvm﹕ VFY: unable to resolve new-instance 155 (Lsun/misc/ServiceConfigurationError;) in Lcom/sun/net/httpserver/spi/HttpServerProvider;
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xacd19b20)
08-02 04:24:37.233 2994-2994/com.ebcompany.hs4 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ebcompany.hs4, PID: 2994
java.lang.NoClassDefFoundError: sun.misc.Service
at com.sun.net.httpserver.spi.HttpServerProvider.loadProviderAsService(HttpServerProvider.java:82)
at com.sun.net.httpserver.spi.HttpServerProvider.access$200(HttpServerProvider.java:27)
at com.sun.net.httpserver.spi.HttpServerProvider$1.run(HttpServerProvider.java:144)
at java.security.AccessController.doPrivileged(AccessController.java:45)
at com.sun.net.httpserver.spi.HttpServerProvider.provider(HttpServerProvider.java:139)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:110)
at com.ebcompany.hs4.HSMainService.onCreate(HSMainService.java:93)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2572)
at android.app.ActivityThread.access$1800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)我该如何解决这个问题?
发布于 2014-08-02 20:29:52
从1.6开始,它应该可以在JDK中使用。否则,您可以单独将其添加到构建路径中。请参阅以下链接:
你可以从http://download.java.net/maven/2/com/sun/net/httpserver/http/20070405/http-20070405.jar下载
发布于 2021-12-26 13:17:09
截至2021年,我不认为这里提供的答案给出了一个直接的解决方案。这是对我有效的方法:
jar文件,其中包含上述com.sun.net.httpserver...类和其他类。您需要告诉Android Studio在该jar文件中查找这些类,以便能够将它们导入到应用程序的java文件中<代码>H19您需要请求<uses-permission android:name="android.permission.INTERNET" />
操作步骤:
jar文件复制到应用程序的libs文件夹(在我的示例中为c:\Android Projects\<Project Name>\app\libs)。您在哪里可以找到这样的文件?所以在我的例子中,我只使用了Android Studio的jre\libs文件夹中的rt.jar文件(在我的例子中是C:\Android Studio\jre\jre\lib\rt.jar)。你可能会因为这是一个60MB的文件而皱眉,但是产生的apk并不比没有httpserver的时候大很多,所以我假设编译器只接受它需要的东西,加上所有的dependencies.
rt.jar文件复制到app/libs后,它应该会出现在您的项目视图中,如果没有,请右键单击应用程序图标,然后单击从磁盘重新加载(参见图2) 
库,然后右键单击新rt.jar文件的图标并选择Add As

我曾尝试将rt.jar文件剥离为更小的文件,但即使我的应用程序可以编译和运行,第一次使用从com.sun.net.*导入的类调用方法时,应用程序也会崩溃(就像在崩溃时一样,而不是引发异常)。因此,您最好包含整个rt.jar文件。下面的示例取自Simple HTTP server in Java using only Java SE API
现在您可以导入
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;在你的应用程序的Activity类中,用以下方法创建一个简单的http服务器:
HttpServer server;
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
System.out.println(t.toString());
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
server = HttpServer.create(new InetSocketAddress(8001), 0);
server.createContext("/ho", new MyHandler());
server.setExecutor(null);
server.start();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}).execute("");
}https://stackoverflow.com/questions/25094834
复制相似问题