java为什么不能使用httpurlconnection发布整个base64字符串?
我想把图像上传到服务器上
- 我得到了图像的位图并将其编码为base64李>
- 我使用encodeToString方法将图像的base64转换为字符串李>
- 我使用httpurlconnection将字符串发布到PHP。实际上,我从PHP中得到的字符串不是整个字符串。我没有发现任何错误。请给我反馈李>
public String httpURLConnectionPost(final String urlString){
String result="";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.NO_CLOSE);
String body= "image="+encodedImage;
Log.d("serverPostData","body = " +body);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
stringBuilder .append(line);
}
result = stringBuilder .toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
php获取字符串并对其进行解码
<?php
include("mysqli_connect.php");
$image= $_POST['image'];
$a = uniqid() ;
$ImagePath = "good/$a.JPEG";
$ServerURL = "https://172.30.10.1/$ImagePath";
$InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;
if(mysqli_query($connect, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($image));
echo $image;
}else{
echo "failed";
}
mysqli_close();
?>
# 1 楼答案
尝试将图像转换为base64:
现在在API中传递数据:
现在设置图像位图:
方法如下:
对于HttpUrlConnection,请尝试以下操作
希望这个对你有用
# 2 楼答案
我解决了base64需要将空替换为“+”的问题