android网络编程之HttpUrlConnection的讲解--POST请求

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对象。

    第三步:设置请求连接属性,传递参数等。

    第四步:获取返回码判断是否链接成功。

    第五步:读取输入流。

    第六步:关闭链接。

posted on 2015-12-19 15:57  StephenHe  阅读(28526)  评论(3编辑  收藏  举报

导航