python作为server端,安卓通过OkHttp3进行访问

首先用Python写出server端代码 ,

这里通过request.form.get()方法来获取POST请求中传递过来的参数url 

from flask import Flask,request
app = Flask(__name__)

@app.route('/', methods = ["POST"])
def post_data():
	url = request.form.get("url",type=str,default=None)
	print('提交链接:')
	return url

if __name__ == '__main__':
    app.run(port=9000,debug= True,host='0.0.0.0')

接收GET请求:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
	return 'hello world'

if __name__ == '__main__':
    app.run(port=8000,debug= True,host='0.0.0.0')

Flask使用文档在这

在AS中写出请求代码:

public static String postUrl = "http://192.168.x.xxx:8000/";
public static String uploadUrl = "http://192.168.x.xxx:9000/";

//向服务端发送GET请求的方法:
private String getRequest(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(postUrl ).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            //请求失败执行的方法
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG,"请求失败!!!");
                Log.d(TAG,"e===="+e.getMessage());

            }
            //请求成功执行的方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG,"请求成功!!!");
                data = response.body().string();
                Log.d(TAG,"返回数据data ======"+data);
            }
        });
        return data;
    }

//向服务端发送POST请求的方法:
private void send(String url){
        OkHttpClient mOkHttpClient=new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("url", url)
                .build();
        Request request = new Request.Builder()
                .url(uploadUrl)
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.e(TAG,"内容上传成功!!!!"+str);
            }
        });
    }

参考资料:https://www.jianshu.com/p/ecd97b1c21c1

你可能感兴趣的:(网络通信,Python,#,Android,Studio)