Set up a local server with Go-File download-

at first

Make a request from the Android app and download the file on the local server where you set up the Web Server with Go

environment

PC Windows10 Android Studio 4.0 Kotlin 1.3.72 Android device Emulator (API Level 29) Go 1.11.1

Diagram

go_server.png Specify the file name from the Android application, request to the server side, return the file and status code saved on the server side

Implementation

Local server

Server.go


package controllers

import (
    "fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"
)

func apiSampleHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		fmt.Println("POST")
	case "GET":                                        //File DL with GET request
		fmt.Println("GET")
		name := fmt.Sprint(r.URL)                      // 「/Get "filename"
		fileName := strings.SplitAfter(name, "/")[1]   //Get "filename"
        //Check if the file exists on the server side
		if fileinfo, err := os.Stat("./" + fileName); os.IsNotExist(err) || fileinfo.IsDir() {
			fmt.Println("file is not exist")
			w.WriteHeader(http.StatusNotFound)
			return
		}
		buf, err := ioutil.ReadFile("./" + fileName)   //Read file
		if err != nil {
			fmt.Println("file could not be read")
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write(buf)                                   //Write to response
	}
	w.WriteHeader(http.StatusOK)
}

// main.Call from go to start the server
func StartWebServer() error {
	http.HandleFunc("/", apiSampleHandler)
	return http.ListenAndServe(":8080", nil)
}

Run main.go and start the server Go to http: // localhost: 8080 and make sure the server is up

Prepare the file

image.png Place the file for download in the same directory as main.go

Android app

1.Androidmanifest.xml

Define Permission to access the Internet

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET" />

Since the http communication setting is turned off from Android 9.0, set uses CleartextTrafic to true

AndroidManifest.xml


<application
abridgement
    android:usesCleartextTraffic="true">
    <activity android:name=".MainActivity">
abridgement
    </activity>
</application>
  1. Server access

Access the server by GET via http communication

Net.kt


   fun requestFileDownload(context: Context, requestUrl: String, fileName: String): Int {
        val url = URL("$requestUrl/$fileName.txt")     //URL object generation
        //UrlConnection object creation
        val urlConnection = url.openConnection() as HttpURLConnection 
        var result = ""
        var responseCode = 0
        try {
            urlConnection.requestMethod = "GET"         // POST,GET etc.
            urlConnection.doInput = true                //Reception of response body
            urlConnection.useCaches = false             //Use of cache
            urlConnection.connect()                     //Establish a connection

            responseCode = urlConnection.responseCode   //Get response code
            when (responseCode) {
                HttpURLConnection.HTTP_OK -> {          //Processed only when response code is 200: OK
                    val path = context.filesDir.toString() + "/" + fileName + FILE_EXPAND
                    //Read the contents of the response
                    DataInputStream(urlConnection.inputStream).use { fileInputStream ->
                        //Create and write a file
                        DataOutputStream(BufferedOutputStream(FileOutputStream(path))).use {
                            val buffer = ByteArray(BUFFER_SIZE)
                            var byteRead: Int
                            do {
                                byteRead = fileInputStream.read(buffer)
                                if (byteRead == -1) {
                                    break
                                }
                                it.write(buffer, 0, byteRead)
                            } while (true)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("Net", "#startConnection$e")
        } finally {
            urlConnection.disconnect()
        }
        return responseCode
    }
}
    1. Confirmation of IP address

Confirm the IP address of the server (PC) you want to access by executing the following with the command prompt

>ipconfig

Four. Connect your PC and Android device to the same network environment

Five. Connect with Android

Set http: // {confirmed IP address}: 8080 in requestUrl of Net # requestFileDownload Set the file name to be downloaded in fileName of Net # requestFileDownload and execute

Confirm file download

Confirm that the file is generated in the application-specific area (under / data / data / {package_name} / files) View files on the device with Device File Explorer (https://developer.android.com/studio/debug/device-file-explorer?hl=ja )

Finally

The whole source is here The access destination, RequestMethod, and file name can be changed dynamically by the application.

Click here to upload files to the server (https://qiita.com/kurramkurram/items/262cd1d2f01dcb6fa8bd)

References

Go server side

Package http Check for the existence of Go language (golang) files and directories [Golang] File reading sample

Android application side

How to download and save a file over HTTP in Java

Recommended Posts

Set up a local server with Go-File download-
Set up a local server with Go-File upload-
Set up a Samba server with Docker
Set up a simple HTTPS server with asyncio
How to set up a local development server
Set up a simple local server on your Mac
[Vagrant] Set up a simple API server with python
Set up a web server with CentOS7 + Anaconda + Django + Apache
Set up a mail server using Twisted
Build a local server with a single command [Mac]
Set up a test SMTP server in Python.
Set up a UDP server in C language
Set up a local web server in 30 seconds using python 3's http.server
Set up a simple SMTP server in Python
Local server with python
Set up a Minecraft resource (Spigot) server via docker (2)
Set up a file server on Ubuntu 20.04 using Samba
Set up a free server on AWS in 30 minutes
[Part 1] Let's set up a Minecraft server on Linux
Set up a Minecraft resource (Spigot) server via docker
Set up a Python development environment with Sublime Text 2
Set up a Python development environment with Visual Studio Code
Reload the server set up with gunicorn when changing the code
Set up social login with Django
Creating a Flask server with Docker
Set up Ubuntu as a Linux cheat sheet and https server
Get a local DynamoDB environment with Docker
Draw a Mandelbrot set with Brainf * ck
Set up reverse proxy to https server with CentOS Linux 8 + Apache mod_ssl
Introduction and usage of Python bottle ・ Try to set up a simple web server with login function
Set up a server that processes multiple connections at the same time
Rock-paper-scissors with Python Let's run on a Windows local server for beginners
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
Start a temporary http server locally with Pytest
Install Windows 10 from a Linux server with PXE
Start a simple Python web server with Docker
Pretend to be a server with two PCs
Launch a web server with Python and Flask
Set up a Python development environment on Marvericks
Mount a directory on another server with sshfs
Create a "Hello World" (HTTP) server with Tornado
How to set up a Google Colab environment with Coursera's advanced machine learning courses
Set up a file server using samba on ZeroPi of Friendly Arm [OS installation]
Build a server on Linux and local network with Raspberry Pi NextCloud and desktop sharing
I want to set up a mock server for python-flask in seconds using swagger-codegen.
Set up a file server using samba on ZeroPi of Friendly Arm [Purchased Items]
Set up a file server using samba on ZeroPi of Friendly Arm [Personal import]
Create an animated GIF local server with Python + Flask
Set up a development environment for natural language processing
How to set up a Python environment using pyenv
I made a ready-to-use syslog server with Play with Docker
A story that struggled with the common set HTTP_PROXY = ~
Set up Docker on Oracle Linux (7.x) with Vagrant
A server that echoes data POSTed with flask / python
Create a home music server with Centos8 + Universal Media Server
[Python] I tried running a local server using flask
A note on speeding up Python code with Numba
Launch Django on a Docker container with docker-compose up
Create a fake Minecraft server in Python with Quarry
I want to bind a local variable with lambda
When it is troublesome to set up an SMTP server locally when sending mail with Python.