Search in sources :

Example 1 with UrlEncodedFormBody

use of com.koushikdutta.async.http.body.UrlEncodedFormBody in project FileTransfer by CPPAlien.

the class WebService method startServer.

private void startServer() {
    server.get("/images/.*", this::sendResources);
    server.get("/scripts/.*", this::sendResources);
    server.get("/css/.*", this::sendResources);
    // index page
    server.get("/", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        try {
            response.send(getIndexContent());
        } catch (IOException e) {
            e.printStackTrace();
            response.code(500).end();
        }
    });
    // query upload list
    server.get("/files", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        JSONArray array = new JSONArray();
        File dir = Constants.DIR;
        if (dir.exists() && dir.isDirectory()) {
            String[] fileNames = dir.list();
            if (fileNames != null) {
                for (String fileName : fileNames) {
                    File file = new File(dir, fileName);
                    if (file.exists() && file.isFile()) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("name", fileName);
                            long fileLen = file.length();
                            DecimalFormat df = new DecimalFormat("0.00");
                            if (fileLen > 1024 * 1024) {
                                jsonObject.put("size", df.format(fileLen * 1f / 1024 / 1024) + "MB");
                            } else if (fileLen > 1024) {
                                jsonObject.put("size", df.format(fileLen * 1f / 1024) + "KB");
                            } else {
                                jsonObject.put("size", fileLen + "B");
                            }
                            array.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        response.send(array.toString());
    });
    // delete
    server.post("/files/.*", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        final UrlEncodedFormBody body = (UrlEncodedFormBody) request.getBody();
        if ("delete".equalsIgnoreCase(body.get().getString("_method"))) {
            String path = request.getPath().replace("/files/", "");
            try {
                path = URLDecoder.decode(path, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File file = new File(Constants.DIR, path);
            if (file.exists() && file.isFile() && file.delete()) {
                RxBus.get().post(Constants.RxBusEventType.LOAD_BOOK_LIST, 0);
            }
        }
        response.end();
    });
    // download
    server.get("/files/.*", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        String path = request.getPath().replace("/files/", "");
        try {
            path = URLDecoder.decode(path, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file = new File(Constants.DIR, path);
        if (file.exists() && file.isFile()) {
            try {
                response.getHeaders().add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.sendFile(file);
            return;
        }
        response.code(404).send("Not found!");
    });
    // upload
    server.post("/files", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        final MultipartFormDataBody body = (MultipartFormDataBody) request.getBody();
        body.setMultipartCallback((Part part) -> {
            if (part.isFile()) {
                body.setDataCallback((DataEmitter emitter, ByteBufferList bb) -> {
                    fileUploadHolder.write(bb.getAllByteArray());
                    bb.recycle();
                });
            } else {
                if (body.getDataCallback() == null) {
                    body.setDataCallback((DataEmitter emitter, ByteBufferList bb) -> {
                        try {
                            String fileName = URLDecoder.decode(new String(bb.getAllByteArray()), "UTF-8");
                            fileUploadHolder.setFileName(fileName);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        bb.recycle();
                    });
                }
            }
        });
        request.setEndCallback((Exception e) -> {
            fileUploadHolder.reset();
            response.end();
            RxBus.get().post(Constants.RxBusEventType.LOAD_BOOK_LIST, 0);
        });
    });
    server.get("/progress/.*", (final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) -> {
        JSONObject res = new JSONObject();
        String path = request.getPath().replace("/progress/", "");
        if (path.equals(fileUploadHolder.fileName)) {
            try {
                res.put("fileName", fileUploadHolder.fileName);
                res.put("size", fileUploadHolder.totalSize);
                res.put("progress", fileUploadHolder.fileOutPutStream == null ? 1 : 0.1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        response.send(res);
    });
    server.listen(mAsyncServer, Constants.HTTP_PORT);
}
Also used : ByteBufferList(com.koushikdutta.async.ByteBufferList) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) DecimalFormat(java.text.DecimalFormat) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) JSONException(org.json.JSONException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(org.json.JSONObject) Part(com.koushikdutta.async.http.body.Part) DataEmitter(com.koushikdutta.async.DataEmitter) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody) File(java.io.File) MultipartFormDataBody(com.koushikdutta.async.http.body.MultipartFormDataBody)

Example 2 with UrlEncodedFormBody

use of com.koushikdutta.async.http.body.UrlEncodedFormBody in project AndroidAsync by koush.

the class HttpServerTests method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    httpServer = new AsyncHttpServer();
    httpServer.setErrorCallback(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            fail();
        }
    });
    httpServer.listen(AsyncServer.getDefault(), 5000);
    httpServer.get("/hello", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            assertNotNull(request.getHeaders().get("Host"));
            response.send("hello");
        }
    });
    httpServer.post("/echo", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
            try {
                assertNotNull(request.getHeaders().get("Host"));
                JSONObject json = new JSONObject();
                if (request.getBody() instanceof UrlEncodedFormBody) {
                    UrlEncodedFormBody body = (UrlEncodedFormBody) request.getBody();
                    for (NameValuePair pair : body.get()) {
                        json.put(pair.getName(), pair.getValue());
                    }
                } else if (request.getBody() instanceof JSONObjectBody) {
                    json = ((JSONObjectBody) request.getBody()).get();
                } else if (request.getBody() instanceof StringBody) {
                    json.put("foo", ((StringBody) request.getBody()).get());
                } else if (request.getBody() instanceof MultipartFormDataBody) {
                    MultipartFormDataBody body = (MultipartFormDataBody) request.getBody();
                    for (NameValuePair pair : body.get()) {
                        json.put(pair.getName(), pair.getValue());
                    }
                }
                response.send(json);
            } catch (Exception e) {
            }
        }
    });
}
Also used : NameValuePair(com.koushikdutta.async.http.NameValuePair) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) HttpServerRequestCallback(com.koushikdutta.async.http.server.HttpServerRequestCallback) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) JSONObjectBody(com.koushikdutta.async.http.body.JSONObjectBody) JSONObject(org.json.JSONObject) StringBody(com.koushikdutta.async.http.body.StringBody) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody) MultipartFormDataBody(com.koushikdutta.async.http.body.MultipartFormDataBody)

Example 3 with UrlEncodedFormBody

use of com.koushikdutta.async.http.body.UrlEncodedFormBody in project AndroidAsync by koush.

the class BodyTests method testNullValue.

@Test
public void testNullValue() throws Exception {
    Multimap mm = new Multimap();
    mm.add("hello", null);
    UrlEncodedFormBody body = new UrlEncodedFormBody(mm);
    int length = body.length();
}
Also used : Multimap(com.koushikdutta.async.http.Multimap) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody) Test(org.junit.Test)

Example 4 with UrlEncodedFormBody

use of com.koushikdutta.async.http.body.UrlEncodedFormBody in project ion by koush.

the class IonRequestBuilder method setBodyParameter.

@Override
public IonRequestBuilder setBodyParameter(String name, String value) {
    if (bodyParameters == null) {
        bodyParameters = new Multimap();
        setBody(new UrlEncodedFormBody(bodyParameters));
    }
    if (value != null)
        bodyParameters.add(name, value);
    return this;
}
Also used : Multimap(com.koushikdutta.async.http.Multimap) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody)

Example 5 with UrlEncodedFormBody

use of com.koushikdutta.async.http.body.UrlEncodedFormBody in project ion by koush.

the class IonRequestBuilder method setBodyParameters.

public IonRequestBuilder setBodyParameters(Map<String, List<String>> params) {
    if (bodyParameters == null) {
        bodyParameters = new Multimap();
        setBody(new UrlEncodedFormBody(bodyParameters));
    }
    bodyParameters.putAll(params);
    return this;
}
Also used : Multimap(com.koushikdutta.async.http.Multimap) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody)

Aggregations

UrlEncodedFormBody (com.koushikdutta.async.http.body.UrlEncodedFormBody)7 Multimap (com.koushikdutta.async.http.Multimap)3 AsyncHttpServerRequest (com.koushikdutta.async.http.server.AsyncHttpServerRequest)3 AsyncHttpServerResponse (com.koushikdutta.async.http.server.AsyncHttpServerResponse)3 NameValuePair (com.koushikdutta.async.http.NameValuePair)2 MultipartFormDataBody (com.koushikdutta.async.http.body.MultipartFormDataBody)2 AsyncHttpServer (com.koushikdutta.async.http.server.AsyncHttpServer)2 HttpServerRequestCallback (com.koushikdutta.async.http.server.HttpServerRequestCallback)2 File (java.io.File)2 IOException (java.io.IOException)2 JSONObject (org.json.JSONObject)2 Bitmap (android.graphics.Bitmap)1 BitmapDrawable (android.graphics.drawable.BitmapDrawable)1 ImageView (android.widget.ImageView)1 AsyncServer (com.koushikdutta.async.AsyncServer)1 ByteBufferList (com.koushikdutta.async.ByteBufferList)1 DataEmitter (com.koushikdutta.async.DataEmitter)1 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)1 AsyncHttpClient (com.koushikdutta.async.http.AsyncHttpClient)1 AsyncHttpPost (com.koushikdutta.async.http.AsyncHttpPost)1