最近在开发Android软件中,要实现手机端向服务器端提交数据,打算采用Android post请求,向服务器端传递字节流,故而写了一个代码原型,代码如下:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); post(getData(), "http://www.android-study.com"); } public byte[] getData() { ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(arrayOutputStream); try { dataOutputStream.writeShort(8); dataOutputStream.writeUTF("wangjun"); dataOutputStream.flush(); dataOutputStream.close(); } catch (Exception e) { throw new RuntimeException(e); } return arrayOutputStream.toByteArray(); } public boolean post(byte[] paramArrayOfByte,String http) { ByteArrayEntity arrayEntity = new ByteArrayEntity(paramArrayOfByte); arrayEntity.setContentType("application/octet-stream"); HttpPost httpPost = new HttpPost(http); httpPost.setEntity(arrayEntity); DefaultHttpClient client = new DefaultHttpClient(); try { int result=client.execute(httpPost).getStatusLine().getStatusCode(); Log.i("huilurry","]]]=" + result); } catch (Exception e) { throw new RuntimeException(e); } return false; } |
|