android上的Http客户端(向服务器发送字符串并获得字符串答案)



我正在实现一个简单的android http客户端,它将通过POST向服务器发送图像,并获得字符串答案。我想那个图像也会以字符串的形式发送,采用Base64格式。

现在,在StackOverflow上,我发现了很多使用HttpClient的例子,但是,它现在被标记为不推荐使用。那么我应该使用什么以及如何使用呢?允许使用外部库。非常欢迎提供一个关于如何向服务器发送Base64字符串并获得字符串答案的代码示例!提前感谢

Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.icon); 
new UploadHandler().execute(icon); // pass your bitmap here....
private static class UploadHandler extends AsyncTask<Bitmap,Void,String>{
@Override
protected String doInBackground(Bitmap... bitmaps) {
try{
return uploadImageToServer(bitmaps[0]);
}catch (Exception ex){
}
return null;
}
@Override
protected void onPostExecute(String s) {
// Update UI here
// Find post request response here and your stuff ...
Log.i("JSON","onPostExecute: " +  s);
}

public static byte[] getEncodedPNGImage(Bitmap bitmap) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
//this will convert image to byte[]
byte[] byteArrayImage = baos.toByteArray();
// this will convert byte[] to string
baos.close();
return byteArrayImage;
}

private String uploadImageToServer(Bitmap myBitmap){
try {
URL url = new URL("your image upload endpoint");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
String data = "{ "image": "" + getEncodedPNGImage(myBitmap) + "" }";
Log.i("JSON", data);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(data);
os.flush();
os.close();
Log.i("JSON","STATUS: " + String.valueOf(conn.getResponseCode()));
final String msg = conn.getResponseMessage();
Log.i("JSON","MSG: " +  msg);

conn.disconnect();
return msg;
} catch (Exception e) {
Log.e("JSON", e.getMessage());
return null;
}
}
}

相关内容

最新更新