我正在尝试使用PHP将图像(在base64中绘制压缩)作为JSONObject从android上传到Web服务。我尝试将HttpURLConnection与方法帖子一起使用。
我的代码,在android中。
try {
JSONObject params = new JSONObject();
params.put("nombre", name);
params.put("img", imgBase64);
Log.d("params", params.toString());
URL url = new URL(urlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//conn.setReadTimeout(5000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
BufferedOutputStream BuffOut = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(BuffOut, "UTF-8"));
writer.write(params.toString());
writer.close();
BuffOut.close();
//open
conn.connect();
//do somehting with response
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader buffr = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = buffr.readLine()) != null) {
sb.append(line);
break;
}
Log.d("leer", sb.toString());
buffr.close();
conn.disconnect();
return sb.toString();
} else {
Log.d("err","false : " + responseCode);
return "false : " + responseCode;
}
} catch (JSONException e) {
return " Exception JSON: " + e.getMessage();
} catch (IllegalStateException e) {
return " IllegalStateException: " + e.getMessage();
} catch (UnsupportedEncodingException e) {
return " UnsupportedEncodingException: " + e.getMessage();
} catch (ProtocolException e) {
return " ProtocolException: " + e.getMessage();
} catch (MalformedURLException e) {
return " MalformedURLException: " + e.getMessage();
} catch (IOException e) {
return " Exception IO: " + e.getMessage();
} catch (Exception e) {
return " Exception: " + e.getMessage();
}
在Logcat中我遇到如下错误:ProtocolException:意外的流结束
在服务器端,php我有:
header('Content-type: application/json');
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(!empty($_POST['nombre'])&&!empty($_POST['img'])){
echo json_encode(array('status' => 'ok', 'msg' => "hi ".$_POST['nombre']. " img ".$_POST['img']));
}
}