這是我使用POST發送到後端的通用方法:
/**
* putJSONObject
*
* @param url
* @param jsonObject
* @param timeoutMillis
* @return
*/
protected static JSONObject putJSONObject (String url, JSONObject jsonObject, int timeoutMillis) throws IOException, JSONException {
StringBuilder stringBuilder = new StringBuilder();
HttpURLConnection httpURLConnection;
DataOutputStream printout;
httpURLConnection = (HttpURLConnection) new URL (url).openConnection();
httpURLConnection.setRequestMethod ("POST");
httpURLConnection.setReadTimeout (timeoutMillis);
httpURLConnection.setConnectTimeout (timeoutMillis);
httpURLConnection.setDoInput (true);
httpURLConnection.setDoOutput (true);
httpURLConnection.setUseCaches (false);
httpURLConnection.connect();
// Send POST output.
printout = new DataOutputStream (httpURLConnection.getOutputStream());
printout.writeBytes ("msg=" + URLEncoder.encode (jsonObject.toString(), "UTF-8"));
printout.flush();
printout.close();
InputStreamReader inputStreamReader = new InputStreamReader (httpURLConnection.getInputStream());
int read;
char[] buff = new char[4096];
while ((read = inputStreamReader.read (buff)) != -1) {
stringBuilder.append (buff, 0, read);
}
httpURLConnection.disconnect();
return new JSONObject (stringBuilder.toString());
}
的JSON發送被作爲「味精」
和圖像編碼到一個字符串,這是我的代碼:
/**
* toBase64
*
* @param bitmap
* @return String
*/
public static String toBase64 (Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
/**
* fromBase64
*
* @param encodedImage
* @return Bitmap
*/
public static Bitmap fromBase64 (String encodedImage) {
byte[] decodedByte = Base64.decode(encodedImage, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
希望它可以幫助你。
哪些是您使用在後端側解析它的語言? –
@WalterPalladino不幸的是我不處理任何服務器端。 –
我添加了一些正在爲我工作的代碼。希望它可以幫助你。就我而言,後端是PHP。 –