android客户端通过HttpURLConnection传递给服务器一个参数,服务器端用flask接收这个参数,请给出代码
时间: 2023-06-03 09:03:33 浏览: 227
好的,以下是客户端和服务器端的示例代码:
客户端代码(Android端):
```
String urlString = "http://your-server-url.com/your-endpoint";
String parameterName = "param";
String parameterValue = "value";
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(parameterName, "UTF-8") + "=" + URLEncoder.encode(parameterValue, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
Log.i(TAG, "Response Code: " + responseCode);
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String response = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
Log.i(TAG, "Response: " + response);
} catch (IOException e) {
e.printStackTrace();
}
```
服务器端代码(Flask端):
```
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def handle_request():
param_value = request.form.get('param')
return 'Received parameter: ' + param_value
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
```
这个示例演示了一个POST请求,POST请求可以在请求体中传递数据,使用`HttpURLConnection`的`setDoOutput(true)`方法后,可以使用`getOutputStream()`方法获取输出流向请求体中写入数据。在服务器端,`Flask`的请求体信息存储在`request.form`中,可以使用`get`方法获取参数的值。
不过需要注意的是,`HttpURLConnection`在Android10及以上版本中已经被废弃,建议使用更为先进的`OkHttp`库替代,但是使用方法类似。
阅读全文