2

I find same problem this Android Retrofit - POST request doesn't work, but in Postman it works

But I could not solve it

this is gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.8.0'
compile 'com.google.code.gson:gson:2.8.0'

this is my code to post request in android

static final String URL = "http://localhost:3000/";

     public void map(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    Map map = new HashMap();
    map.put("gender", UserSex);
    map.put("age", UserAge);
    map.put("name", UserName);
    map.put("password", UserPw);
    map.put("email", UserEmail);

    GitHubService gitHubService = retrofit.create(GitHubService.class);
    Call<RetrofitRepo> call = gitHubService.getUserItem(map);
    call.enqueue(new Callback<RetrofitRepo>() {
        @Override
        public void onResponse(Call<RetrofitRepo> call, Response<RetrofitRepo> response) {
            try {
                RetrofitRepo repoList = response.body();
                String message = repoList.getmessage();
                String token = repoList.gettoken();

                if (message.equals("registered successfully")) {
                    Intent intent = new Intent(UserEnroll.this, LoginActivity.class);
                    startActivity(intent);
                    Toast.makeText(context, "register success.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "register failed.", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<RetrofitRepo> call, Throwable t) {

        }
    });
}

and this is interface

public interface GitHubService {

@FormUrlEncoded
@POST("api/auth/login")
Call<RetrofitRepo> getPost(
        @Field("username") String username
);

@FormUrlEncoded
@POST("api/auth/placeSearch")
Call<RetrofitRepo> getPlaceID(
        @Field("placeID") String placeID
);

@FormUrlEncoded
@POST("api/auth/login")
Call<RetrofitRepo> getItem(
        @FieldMap Map<String, String> option
);

@FormUrlEncoded
@POST("api/auth/register")
Call<RetrofitRepo> getUserItem(
        @FieldMap Map<String, String> option
);

}

i use node js this is response code

exports.register = (req, res) => {
const { email, password, name, age, gender } = req.body
let newUser = null

const create = (user) => {
    if(user) {
        throw new Error('email exists')
    } else {
        return User.create(email, password, name, age, gender)
    }
}

const count = (user) => {
    newUser = user
    return User.count({}).exec()
}

const assign = (count) => {
    if(count === 1) {
        return newUser.assignAdmin()
    } else {
        return Promise.resolve(false)
    }
}

const respond = (isAdmin) => {
    res.json({
        message: 'registered successfully',
        admin: isAdmin ? true : false
    })
}

const onError = (error) => {
    res.status(409).json({
        message: error.message
    })
}

User.findOneByEmail(email)
.then(create)
.then(count)
.then(assign)
.then(respond)
.catch(onError)}

I requested using a postman and it worked

http://localhost:3000/api/auth/register
{
"email": "test6@google.com",
"password": "abc123@",
"name": "user",
"age": "18",
"gender": "F"}

POST /api/auth/register 409 13.393 ms - 26 or POST /api/auth/register 200 15.064 ms - 51 it responded in node

but its not work on my android app using retrofit and not responded in node

Jshin
  • 131
  • 2
  • 9

2 Answers2

2
  1. Check Whether you had put your Server OnLine
  2. Verify the URL that you had Requested is Correct.
  3. If you are using Emulator use IP as 10.0.2.2 and if a real device is using use same network and use IP of the System

static final String URL = "http://IPADRESSOFSERVER:3000/";

For Emulator use static final String URL = "http://10.0.2.2:3000/";

Use same network for connecting to local network. and Use the Ip Adderess of the System. Turn off the System Firewall and Antivirus too.

Open your browser (Chrome Recommended) and type "http://IPADRESSOFSERVER:3000/someWebpageHOstedOnline". IF it is accessable check the retrofit call. else the Device cant create connection to the server

Add

app.get('/test',function(req,res){
    res.send(Hello This is a Test);
});

in your js file and try accessing http://IPADRESSOFSERVER:3000/test

Tomin B Azhakathu
  • 2,656
  • 1
  • 19
  • 28
  • i checked that 1. yes server is online 2. URL is correct 3. i'm not using emulator and i try my ip but its not work.. thank you for your suggestions. if you know other solution please tell me – Jshin Apr 24 '18 at 06:05
  • @Jshin Open your browser (Chrome Recommended) and type "http://IPADRESSOFSERVER:3000/someWebpageHOstedOnline". IF it is accessable check the retrofit call. else the Device cant create connection to the server. This is to check whether device is connecting to the Server properly . – Tomin B Azhakathu Apr 24 '18 at 06:09
  • use ipadress of the system always instead of localhost. And make sure that the port is open for extenal connection by turning of firwall ad by adding inbound law – Tomin B Azhakathu Apr 24 '18 at 06:11
  • @Jshin may be your firewall blocks an outside request. Check it by the above method. – Tomin B Azhakathu Apr 24 '18 at 06:16
  • i try that pc and mobile, pc "http://ipaddress:3000/api/auth/register" is correct response but mobile is responded timed out error and i use wifi router in my pc. Is this related to the problem? – Jshin Apr 24 '18 at 06:50
  • which os are you using? – Tomin B Azhakathu Apr 24 '18 at 06:51
  • Did you try it by turning of both firewall and ativirus. The timeout occurs due to your mobile device cant access the server – Tomin B Azhakathu Apr 24 '18 at 06:53
  • i using windows 10 on my pc – Jshin Apr 24 '18 at 06:53
  • Turn of windows firewall, defender and antivirus. Add a url in your js file and test whether it can be accessed using the chrome – Tomin B Azhakathu Apr 24 '18 at 06:56
  • 1
    really thank you! i turn off the window firewall, antivirus and i restart server its work! Thank you so much bro! – Jshin Apr 24 '18 at 07:00
  • Happy to hear that Bro. Thank You. Happy Coding Bro – Tomin B Azhakathu Apr 24 '18 at 07:01
0

Your need to user your computer or laptop's IP Address in your base URL

static final String URL = "http://yourIPAddress:3000/";

example :

static final String URL = "http://192.168.0.100:3000/";

Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71