1、服務器后台使用Servlet開發,這里不再介紹。
2、網絡開發不要忘記在配置文件中添加訪問網絡的權限
<uses-permission android:name="android.permission.INTERNET"/>
3、網絡請求、處理不能在主線程中進行,一定要在子線程中進行。因為網絡請求一般有1~3秒左右的延時,在主線程中進行造成主線程的停頓,對用戶體驗來說是致命的。(主線程應該只進行UI繪制,像網絡請求、資源下載、各種耗時操作都應該放到子線程中)。
4、
public class PostActivity extends Activity { private TextView mTvMsg; private String result = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_post); initView(); } private void initView(){ mTvMsg = (TextView) findViewById(R.id.tv_msg); new Thread(postThread).start(); } private Thread postThread = new Thread(){ public void run() { HttpURLConnection connection = null; try { URL url = new URL("http://192.168.23.1:8080/TestProject/PostTest"); connection = (HttpURLConnection) url.openConnection(); // 設置請求方式 connection.setRequestMethod("POST"); // 設置編碼格式 connection.setRequestProperty("Charset", "UTF-8"); // 傳遞自定義參數 connection.setRequestProperty("MyProperty", "this is me!"); // 設置容許輸出 connection.setDoOutput(true); // 上傳一張圖片 FileInputStream file = new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/Pictures/Screenshots/Screenshot_2015-12-19-08-40-18.png"); OutputStream os = connection.getOutputStream(); int count = 0; while((count=file.read()) != -1){ os.write(count); } os.flush(); os.close(); // 獲取返回數據 if(connection.getResponseCode() == 200){ InputStream is = connection.getInputStream(); result = StringStreamUtil.inputStreamToString(is); Message msg = Message.obtain(); msg.what = 0; postHandler.sendMessage(msg); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(connection!=null){ connection.disconnect(); } } }; }; private Handler postHandler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg.what==0 && result!=null){ mTvMsg.setText(result); } }; }; }
5、

6、上傳Json字符串很長的話可以考慮將Json字符串作為字節流上傳,不過要指明Json字符串的長度:Json的長度+Json+文件流。服務器端就可以根據Json的長度,區分Json和文件流。
7、上傳大文件時,可能出現崩潰。我們可以設置一下HttpUrlConnection。
// 設置每次傳輸的流大小,可以有效防止手機因為內存不足崩潰 // 此方法用於在預先不知道內容長度時啟用沒有進行內部緩沖的 HTTP請求正文的流。 connection.setChunkedStreamingMode(51200); // 128K
8、第一步:實例化URL對象。
第二步:實例化HttpUrlConnection對象。
第三步:設置請求連接屬性,傳遞參數等。
第四步:獲取返回碼判斷是否鏈接成功。
第五步:讀取輸入流。
第六步:關閉鏈接。
