我需要使用HTTP发布将Android应用程序中的Base64字符串发送到Python Web服务。 我想接收该字符串并将其返回到网页上,但是问题是我无法接收该字符串。
在Android方面,我从存储中选择了一个文件,并将其编码为base64字符串。然后,我使用Volley发出HTTP发布请求。 另一方面,我使用Flask构建了Web服务。
这是我的Android应用程序的MainActivity:
public class MainActivity extends AppCompatActivity {
Button button1;
Intent intent;
TextView text;
private static final int READ_REQUEST_CODE = 42;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
text = findViewById(R.id.text);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("application/vnd.android.package-archive");
startActivityForResult(intent, READ_REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
uri = data.getData();
//Toast.makeText(MainActivity.this, uri.toString(), Toast.LENGTH_LONG).show();
try {
final String conv = readTextFromUri(uri);
//text.setText(conv);
////////REQUEST////////
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.0.2.2:5000";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
text.setText("Response is: "+ response.substring(0,500));
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
text.setText("That didn't work!");
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("conv", conv);
return params;
}
};
queue.add(postRequest);
////////END_REQUEST////////
}
catch (IOException e) {
}
}
}
////////ENCODE/////////
private String readTextFromUri(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
output64.close();
String attachedFile = output.toString();
return attachedFile;
}
////////THE END OF ENCODE////////
}
这是我的Python Web服务:
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def call_cortex():
if request.method == 'POST':
fileb64 = request.form['conv']
return fileb64
else:
return 'Errore!'
目前,结果是:
Android应用程序显示
Response is + (part of base64 string)
Web服务显示“错误!”那是
Method Not Allowed