需求:android 客户端上传图片到C#服务端。
Android端:
*************************************************************************************************************************
//Base64.DEFAULT当字符串过长(一般超过76)时会自动在中间加一个换行符,字符串最后也会加一个换行符,这样就导致和其他模块对接时结果不一致 。由于图片太大,所有参数不能用DEFAULT,而用NO_WRAP。
String baseStr = new String (Base64.encode(fileByte,Base64.NO_WRAP), Charset.forName("ISO-8859-1"));
//Charset.forName("ISO-8859-1")我加上了这个测试是可以用的,但删除之后是否可用,未测试。
http post:
public static String httpPost(String url, String param) {
String result = "";
URL localURL = null;
try {
localURL = new URL(url);
} catch (MalformedURLException e) {
result = e.getMessage();
return result;
}
URLConnection connection = null;
try {
connection = localURL.openConnection();
} catch (IOException e) {
result = e.getMessage();
return result;
}
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
try {
httpURLConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
result = e.getMessage();
return result;
}
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
httpURLConnection.setConnectTimeout(10000);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(param.toString());
outputStreamWriter.flush();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode >= 300) {
result = "HTTP Request is not success, Response code is " + responseCode;
}
inputStream = httpURLConnection.getInputStream();
result = convertStreamToString(inputStream);
System.out.println(result);
} catch (Exception e) {
result = e.getMessage();
return result;
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}catch (Exception e){
result = e.getMessage();
return result;
}
}
return result;
}
http 调用方式:
String url = path+"/uploadImage";
String param = "cid="+cid+"&imageStr="+imageStr;;
httpPost(url,param);
*************************************************************************************************************************
C#端:
public string uploadImage(string cid, string imageStr){
string dummyData = imageStr.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
if (dummyData.Length % 4 > 0)
{
dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
}
byte[] imageFileByte = Convert.FromBase64String(dummyData);
}