Simple Spider Web Server Supply Icon Download, Using Org.Apache.Http.Protocol.Httpservice

Posted on

Last postal service exhibit a “Simple spider web server using org.apache.http.protocol.HttpService“. In this post, I tried to furnish icon download, yesteryear visiting http://<ip address>:8080/image

But FAIL – As shown inward the video, sometimes the download volition fail. And in i trial fail, the code volition block together with cause got to live re-start. Hope anybody tin advise.


Modify MainActivity.java

package com.example.androidhttpservice;  import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Enumeration;  import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.entity.ContentProducer; import org.apache.http.entity.EntityTemplate; import org.apache.http.entity.FileEntity; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpServerConnection; import org.apache.http.params.BasicHttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandlerRegistry; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer;  import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import android.os.Bundle; import android.os.Environment;  /*  * Permission needed:  * "android.permission.INTERNET"  * "android.permission.READ_EXTERNAL_STORAGE"  */  world shape MainActivity extends ActionBarActivity {   HttpServiceThread httpServiceThread;    TextView infoIp;   @Override  protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);    infoIp = (TextView) findViewById(R.id.infoip);   infoIp.setText(getIpAddress() + ":"      + HttpServiceThread.HttpServerPORT + "\n");    httpServiceThread = novel HttpServiceThread();   httpServiceThread.start();  }   @Override  protected void onDestroy() {   super.onDestroy();   httpServiceThread.stopServer();  }   someone String getIpAddress() {   String ip = "";   endeavor {    Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface      .getNetworkInterfaces();    field (enumNetworkInterfaces.hasMoreElements()) {     NetworkInterface networkInterface = enumNetworkInterfaces       .nextElement();     Enumeration<InetAddress> enumInetAddress = networkInterface       .getInetAddresses();     field (enumInetAddress.hasMoreElements()) {      InetAddress inetAddress = enumInetAddress.nextElement();       if (inetAddress.isSiteLocalAddress()) {       ip += "SiteLocalAddress: "         + inetAddress.getHostAddress() + "\n";      }      }     }    } grab (SocketException e) {    // TODO Auto-generated grab block    e.printStackTrace();    ip += "Something Wrong! " + e.toString() + "\n";   }    render ip;  }   someone shape HttpServiceThread extends Thread {    ServerSocket serverSocket;   Socket socket;   HttpService httpService;   BasicHttpContext basicHttpContext;   static terminal int HttpServerPORT = 8080;   boolean RUNNING = false;    HttpServiceThread() {    RUNNING = true;    startHttpService();   }    @Override   world void run() {     endeavor {     serverSocket = novel ServerSocket(HttpServerPORT);     serverSocket.setReuseAddress(true);      field (RUNNING) {      socket = serverSocket.accept();            DefaultHttpServerConnection httpServerConnection = novel DefaultHttpServerConnection();      httpServerConnection.bind(socket, novel BasicHttpParams());      httpService.handleRequest(httpServerConnection,        basicHttpContext);      httpServerConnection.shutdown();     }     serverSocket.close();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    } grab (HttpException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }   }    someone synchronized void startHttpService() {    BasicHttpProcessor basicHttpProcessor = novel BasicHttpProcessor();    basicHttpContext = novel BasicHttpContext();     basicHttpProcessor.addInterceptor(new ResponseDate());    basicHttpProcessor.addInterceptor(new ResponseServer());    basicHttpProcessor.addInterceptor(new ResponseContent());    basicHttpProcessor.addInterceptor(new ResponseConnControl());     httpService = novel HttpService(basicHttpProcessor,      novel DefaultConnectionReuseStrategy(),      novel DefaultHttpResponseFactory());     HttpRequestHandlerRegistry registry = novel HttpRequestHandlerRegistry();    registry.register("/", novel HomeCommandHandler());    registry.register("/image", novel ImageCommandHandler());    httpService.setHandlerResolver(registry);   }    world synchronized void stopServer() {    RUNNING = false;    if (serverSocket != null) {     endeavor {      serverSocket.close();     } grab (IOException e) {      // TODO Auto-generated grab block      e.printStackTrace();     }    }   }    shape HomeCommandHandler implements HttpRequestHandler {     @Override    world void handle(HttpRequest request, HttpResponse response,      HttpContext httpContext) throws HttpException, IOException {      HttpEntity httpEntity = novel EntityTemplate(       novel ContentProducer() {         world void writeTo(final OutputStream outstream)          throws IOException {          OutputStreamWriter outputStreamWriter = novel OutputStreamWriter(           outstream, "UTF-8");         String reply = "<html><head></head><body><h1>Hello HttpService, from <h1></body></html>";          outputStreamWriter.write(response);         outputStreamWriter.flush();        }       });     response.setHeader("Content-Type", "text/html");     response.setEntity(httpEntity);    }    }      shape ImageCommandHandler implements HttpRequestHandler {     @Override    world void handle(HttpRequest request, HttpResponse response,      HttpContext context) throws HttpException, IOException {      File file = novel File(       Environment.getExternalStorageDirectory(),        "android-er_sketch.jpg");                  FileEntity fileEntity = novel FileEntity(file, "image/jpg");                 response.setHeader("Content-Type", "application/force-download");                 response.setHeader("Content-Disposition","attachment; filename=image.jpg");     response.setHeader("Content-Type", "image/jpg");     response.setEntity(fileEntity);    }       }   }  } 

Layout file, activity_main.xml, refer to last post.

Permission of “android.permission.INTERNET” together with “android.permission.READ_EXTERNAL_STORAGE” is needed inward AndroidManifest.xml.

  world shape MainActivity extends ActionBarActivity  Simple spider web server furnish icon download, using org.apache.http.protocol.HttpServiceDownload the files.