复习URLHttpConnection方式GET,POST方式链接网络解析uri

来源:互联网 发布:攻击app软件 编辑:程序博客网 时间:2024/06/03 18:56
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.xh.tx.postget.MainActivity" >  <EditText       android:id="@+id/et_username"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:hint="请输入用户名"          />  <EditText       android:id="@+id/et_password"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:layout_below="@id/et_username"      android:hint="请输入密码"           />    <Button       android:id="@+id/bt_get"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:layout_below="@id/et_password"      android:text="GET提交"      />      <Button       android:id="@+id/bt_post"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:layout_below="@id/bt_get"      android:text="POST提交"      /></RelativeLayout>

netutils

package com.xh.tx.netUtils;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.ProtocolException;import java.net.URL;import java.net.URLEncoder;public class NetUtils {    public static String getSubmit(String username,String password,String uri)    {        uri = uri +"?username=" + username + "&password=" + password;                HttpURLConnection conn =  getHttpURLConnection(uri);        // http://localhost:8080/TestServlet?username=zs&password=123                try {            conn.setConnectTimeout(30000);            conn.setReadTimeout(30000);            conn.setRequestMethod("GET");                        conn.connect(); //连接 连接的时候是否要传递参数过去                        //先判断一下状态是否为200,如果为200则将in流转换为字符串            if(conn.getResponseCode() == 200)            {                String content = getStringFromInputStream(conn.getInputStream());                                return content;            }                    } catch (ProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }                return null;    }        private static String getStringFromInputStream(InputStream inputStream) throws IOException    {        byte[] buffer = new byte[1024];        ByteArrayOutputStream bytearray = new ByteArrayOutputStream();        int len = 0;                while((len = inputStream.read(buffer, 0, 1024)) != -1)        {            bytearray.write(buffer);        }            //    String content = new String(bytearray.toByteArray(),"GBK");                return bytearray.toString();    }    public static String postSubmit(String username,String password, String uri)    {        HttpURLConnection conn =  getHttpURLConnection(uri);                try {            conn.setConnectTimeout(30000);            conn.setReadTimeout(30000);            conn.setRequestMethod("POST");            //如果你要兼容2.3版本,那么你必须添加一下这句话            conn.setDoInput(true);                        //参数传递            OutputStream out = conn.getOutputStream();                        conn.connect();            out.write(("username="+username + "&password=" + password).getBytes());                        if(conn.getResponseCode() == 200)            {                String content = getStringFromInputStream(conn.getInputStream());                return content;            }        } catch (ProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }                return null;    }        public static HttpURLConnection getHttpURLConnection(String uri)    {        try {            URL url = new URL(uri);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();                        return conn;        } catch (IOException e) {            e.printStackTrace();        }        return null;            }}
MainActivity

package com.xh.tx.postget;import com.xh.tx.netUtils.NetUtils;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener {    EditText et_username;    EditText et_password;        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                et_username = (EditText) findViewById(R.id.et_username);        et_password = (EditText) findViewById(R.id.et_password);                findViewById(R.id.bt_get).setOnClickListener(this);        findViewById(R.id.bt_post).setOnClickListener(this);            }    @Override    public void onClick(View v)     {        final String username = et_username.getText().toString();        final String password = et_password.getText().toString();                switch (v.getId()) {        case R.id.bt_get:            new Thread(new Runnable()            {                @Override                public void run()                {                    final String status = NetUtils.getSubmit(username, password,"http://10.0.2.2:8080/baidu/LoginServelt");                                        runOnUiThread(new Runnable() {                        @Override                        public void run()                         {                            Toast.makeText(MainActivity.this, "返回的状态为:" + status, 0).show();                        }                    });                }            }).start();            break;        case R.id.bt_post:            new Thread(new Runnable()            {                @Override                public void run()                {                    final String status = NetUtils.postSubmit(username, password,"http://10.0.2.2:8080/baidu/LoginServelt");                                        runOnUiThread(new Runnable() {                        @Override                        public void run()                         {                            Toast.makeText(MainActivity.this, "返回的状态为:" + status, 0).show();                        }                    });                }            }).start();            break;        default:            break;        }    }}


0 0
原创粉丝点击