我在java中使用以下函数连接到服务器中的php脚本。 该脚本查询图像(BLOB),对其进行编码(base64)并以JSON格式将其发回。
问题是我可以获得一些编码数据但不是全部。我应该在httpRequest上使用任何标头吗?我做错了什么?
这是我的java函数:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("Print1: "+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return null;
}
System.out.println("Print2: "+jObj.toString());
// return JSON String
return jObj;
}
这是我的PHP代码,显示了JSON结构:
$response = array(
"success" => 0,
"message" => "",
"data" => "");
$stmt->bindColumn(1, $binary, PDO::PARAM_LOB);
$stmt->bindColumn(2, $professorName);
$stmt->fetch(PDO::FETCH_BOUND);
$pic = base64_encode($binary);
$data = array(
"photo" => $pic,
"professorName" => $professorName
);
$response["success"] = 1;
$response["message"] = "We have results!";
$response["data"] = $data;
echo json_encode($response);
经过测试,我意识到如果我使用一个小图像(测试尺寸<1Kb),一切都会正常工作。
如果我尝试获得更大的图像(此处为5 Kb),我获得的数据将在中间切割。 json结构没有完成。
以下是成功转移的示例:
Print1: {"success":1,"message":"We have results!","data":
{"photo":"iVBORw0KGgoAAAANS~~~~more data~~~~N6GGYzAAAAAElFTkSuQmCC","professorName":"cluvas"}}
Print2: {"data":{"kathigitisName":"cluvas","photo":"iVBORw0K~~~~more data~~~~AElFTkSuQmCC"},
"message":"We have results!","success":1}
这是一个不成功的例子
Print1: {"success":1,"message":"We have results!","data":
{"photo":"\/9j\/4AAQS~~~~more data~~~~6KKogkH\/ //unexpected end of data
Print2: {"data":{"professorName":"cluvas",
"photo":"\/9j\/4AAQS~~~~more data~~~~K+U\/Ce //unexpected end of data