代码之家  ›  专栏  ›  技术社区  ›  Jshin

Android改装POST请求不起作用,但在Postman中起作用

  •  2
  • Jshin  · 技术社区  · 7 年前

    我发现同样的问题 Android Retrofit - POST request doesn't work, but in Postman it works

    但我解决不了

    我是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'
    

    这是我在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) {
    
            }
        });
    }
    

    这是接口

    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
    );
    

    }

    我使用节点js这是响应代码

    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)}
    

    我请求找个邮递员,结果成功了

    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或 POST/api/auth/register 200 15.064 ms-51它在节点中响应

    但它在我的android应用程序上无法使用改型 并且在节点中未响应

    2 回复  |  直到 7 年前
        1
  •  2
  •   Tomin B Azhakathu    7 年前
    1. 检查您是否已将 服务器联机
    2. 验证 URL地址 你要求的是 对的
    3. 如果您使用的是Emulator,请按照10.0.2.2使用IP,如果实际设备使用的是相同的网络,请使用系统的IP

    静态最终字符串URL=“” http://IPADRESSOFSERVER:3000/ “;

    供模拟器使用 静态最终字符串URL=“” http://10.0.2.2:3000/ “;

    使用 连接到本地网络的相同网络 。并使用 系统Ip地址 关掉 这个 系统防火墙和防病毒

    打开浏览器(建议使用Chrome),然后键入“ http://IPADRESSOFSERVER:3000/someWebpageHOstedOnline “。如果可以访问,请检查改装呼叫。否则设备无法创建到服务器的连接。”

    添加

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

    在js文件中,尝试访问 http://IPADRESSOFSERVER:3000/test

        2
  •  0
  •   Saurabh Mistry    7 年前

    您需要在基本URL中使用计算机或笔记本电脑的IP地址

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

    示例:

    静态最终字符串URL=“” http://192.168.0.100:3000/ “;