Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

php - how to use localhost in conjunction with retrofit for testing of android apps kotlin

I'm using xammp to test my backend scripting and I just need to get some JSON with retrofit. I have tried following tutorials online but to no avail. I get the error code

    java.net.ConnectException: Failed to connect to /127.0.0.1:80

Whether I'm using localhost as the baseURL or the Ip address of localhost/xammp server or Whether I explicitly use the port or not, I get this error message or something like stated above. edit: upon closer inspection of the error log it also says:

     Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)

and

     Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80) from /127.0.0.1 (port 58156) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)

could this have anything to do with it?

my full jsontest.php

{
    "resoponse": {
        "check": "ahhhhhhhh"
    },
    "Mlist": [{
            "text1": "text1a",
            "text2": "text2a",
            "text3": "text3a"
        },
        {
            "text1": "text1b",
            "text2": "text2b",
            "text3": "text3b"
        },
        {
            "text1": "text1c",
            "text2": "text2c",
            "text3": "text3c"
        }
    ]
}

simple api.kt

interface SimpleApi {
    @GET("jsontest.php")
    suspend fun phonehome(): Phone
}

main fragment.kt

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_main, container, false)
        mUserViewModel = ViewModelProvider(this).get(ViewModel::class.java)

            //other code

            TestGet()

        return view
    }
val BASE_URL = "http://127.0.0.1/"
    private fun TestGet() {

        val api = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(SimpleApi::class.java)

        GlobalScope.launch(Dispatchers.IO) {
          // doing stuff with response
        }
}

if you could point me in the right direction I would be very thankful

thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is your server running on the same device as your Android app? Only then you can use localhost/127.0.0.1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...