需求: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);
}