• android post请求


    参考文章:http://blog.csdn.net/lotusyangjun/article/details/22292445

                  http://blog.csdn.net/withiter/article/details/19908679

    代码如下:

    package tdrhedu.com.edugame;
    import android.content.Intent;
    import android.graphics.Paint;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * Created by zhaoliang on 2016/6/15.
     */
    public class Login2Activity extends AppCompatActivity {
        private static final String TAG = "Login2Activity";
        Button mLogin = null;
        TextView mForgetPassword = null;
        TextView mJustSee = null;
        EditText mAccountName, mAccountPasswd;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login2);
    
            View v = findViewById(R.id.mLoginGuide);//找到你要设透明背景的layout 的id
            v.getBackground().setAlpha(70);//0~255透明度值
    
            //TextView tv = (TextView)findViewById(R.id.find_password);
            //tv.setPaintFlags(tv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
    
            mLogin = (Button) findViewById(R.id.account_login);
            mLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "click");
    
                    String postReceiverUrl = "http://112.126.64.235:9090/company/get";
                    Log.v(TAG, "postURL: " + postReceiverUrl);
    
                    new Thread(new Runnable(){
                        @Override
                        public void run() {
                            mAccountName = (EditText)findViewById(R.id.account_name);
                            mAccountPasswd = (EditText)findViewById(R.id.account_password);
                            String username = mAccountName.getText().toString();
                            String password = mAccountPasswd.getText().toString();
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("username", username);
                            params.put("password", password);
                            String result = submitPostData(params, "utf-8");
                            Log.v(TAG, "result: " + result);
                        }
                    }).start();
    
    
                    //Intent i = new Intent(Login2Activity.this, PannelActivity.class);
                    //startActivity(i);
    
                }
            });
    
            /*mForgetPassword = (TextView) findViewById(R.id.find_password);
            mForgetPassword.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Login2Activity.this, ForgotActivity.class);
                    startActivity(i);
                }
            });
    
            mJustSee = (TextView) findViewById(R.id.just_see);
            mJustSee.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                }
            });*/
    
        }
    
        /*
         * Function  :   发送Post请求到服务器
         * Param     :   params请求体内容,encode编码格式
         * Author    :   zhaoliang@deepai.com
         */
        public static String submitPostData(Map<String, String> params, String encode) {
    
            byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体
            try {
                URL url = new URL("http://112.126.64.235:9090/company/get");
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setConnectTimeout(3000);  //设置连接超时时间
                httpURLConnection.setDoInput(true);                  //打开输入流,以便从服务器获取数据
                httpURLConnection.setDoOutput(true);                 //打开输出流,以便向服务器提交数据
                httpURLConnection.setRequestMethod("POST");   //设置以Post方式提交数据
                httpURLConnection.setUseCaches(false);        //使用Post方式不能使用缓存
                //设置请求体的类型是文本类型
                httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                //设置请求体的长度
                httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
                //获得输出流,向服务器写入数据
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(data);
    
                int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
                if(response == HttpURLConnection.HTTP_OK) {
                    InputStream inptStream = httpURLConnection.getInputStream();
                    return dealResponseResult(inptStream);                     //处理服务器的响应结果
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }
    
        /*
         * Function  :   封装请求体信息
         * Param     :   params请求体内容,encode编码格式
         * Author    :   zhaoliang@deepai.com
         */
        public static StringBuffer getRequestData(Map<String, String> params, String encode) {
            StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
            try {
                for(Map.Entry<String, String> entry : params.entrySet()) {
                    stringBuffer.append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), encode))
                            .append("&");
                }
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuffer;
        }
    
        /*
         * Function  :   处理服务器的响应结果(将输入流转化成字符串)
         * Param     :   inputStream服务器的响应输入流
         * Author    :   zhaoliang@deepai.com
         */
        public static String dealResponseResult(InputStream inputStream) {
            String resultData = null;      //存储处理结果
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int len = 0;
            try {
                while((len = inputStream.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            resultData = new String(byteArrayOutputStream.toByteArray());
            return resultData;
        }
    
    }

    完毕。

  • 相关阅读:
    .NET程序运行原理及基本概念详解
    c# 操作Redis的五种基本类型总结
    手写MQ框架(一)-准备启程
    手写MVC框架(二)-代码实现和使用示例
    手写DAO框架(七)-如何保证连接可用
    spring cloud入门
    maven学习整理
    mybatis入门学习
    spring事务使用探究
    微内核OS学习
  • 原文地址:https://www.cnblogs.com/zl0372/p/android_post.html
Copyright © 2020-2023  润新知