Make a request from the Android app and download the file on the local server where you set up the Web Server with Go
PC Windows10 Android Studio 4.0 Kotlin 1.3.72 Android device Emulator (API Level 29) Go 1.11.1
Specify the file name from the Android application, request to the server side, return the file and status code saved on the server side
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
Place the file for download in the same directory as main.go
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>
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
}
}
Confirm the IP address of the server (PC) you want to access by executing the following with the command prompt
>ipconfig
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 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
)
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)
Package http Check for the existence of Go language (golang) files and directories [Golang] File reading sample
How to download and save a file over HTTP in Java
Recommended Posts