我正在尝试在我的Android应用中上传图片文件,但我收到的响应代码 400 和 responseMessage = null 。 API接受image file
和另外一个额外字段作为POST消息。
以下是我的代码:
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
我的上面的函数在文件RequestHandler中定义,它从Activity调用如下:
public void uploadImage(){
final String text = editText.getText().toString().trim();
final String image = getStringImage(bitmap);
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(FileUploadActivity.this,"Please wait...","uploading",false,false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(FileUploadActivity.this,s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TEXT,text);
param.put(KEY_IMAGE,image);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
EDIT2: 以下函数也是RequestHandler
的一部分private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
答案 0 :(得分:0)
Http 400表示&#34;错误请求。服务器无法理解请求...&#34;首先,您应该首先展示如何在getPostDataString()函数中撰写请求。
我打赌你没有使用多部分表单数据。见SO answer
答案 1 :(得分:0)
我无法发表评论,所以我提供了答案。这是一个奇怪的API。你确定你理解正确吗?您使用POST方法,但不提供内容类型。这既不是JSON也不是XML。这是像URL请求那样的纯字符串格式。服务器返回400并不奇怪。检查API说明。