okhttp与远程服务器通信不上,本地服务器可以通信 5C

在做安卓客户端和python服务端的通信。在app上输入用户名和密码发给服务端,我在本地运行py文件可以实现通信。但是我把py文件传到服务器上启动就不能返回结果。请教各位大神,初次接触这方面。
服务端用的简单的flask,代码如下

from flask import Flask
from flask import request
import os

app = Flask(__name__)

@app.route('/')
def test():
    return '服务器正常运行'



#此方法处理用户注册
@app.route('/register',methods=['POST'])
def register():
    username=request.form['username']
    password=request.form['password']

    print('username:'+username)
    print('password:'+password)
    return '注册成功'

if __name__ == '__main__':
    app.run(host='0.0.0.0')

Android的代码:

private void SendMessage(String url, final String userName, String passWord) {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder formBuilder = new FormBody.Builder();
        formBuilder.add("username", userName);
        formBuilder.add("password", passWord);
        Request request = new Request.Builder().url(url).post(formBuilder.build()).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String res = response.body().string();
                System.out.println("3333333333333333333");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (res.equals("0")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "该用户名已被注册", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
                                }
                            });

                        }

                    }
                });
            }
        });
sinat_38501620
glam 已解决。是因为服务器的对应端口没有开放
2 个月之前 回复

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问