HttpURLConnection的GET和POST请求

效果图:

HttpURLConnection的GET和POST请求_第1张图片

主页面代码:

public class HttpActivity extends Activity {
    private TextView tv_Http;
    private String str_result;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);

        tv_Http = (TextView) findViewById(R.id.iv_http);

        new Thread(new LoadThread()).start();
    }


    public class LoadThread implements Runnable {

        @Override
        public void run() {
            try {
                URL url = new URL("http://www.baidu.com");//Get请求带参数的URL: "www.baidu.com?id=2111&name="+ URLEncoder.encode("张三", "utf-8");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                //-----------------------------GET请求-------------------------------
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);//设置连接超时时间
                connection.setReadTimeout(8000);//设置读取超时时间
                connection.connect();// 进行连接,但是实际上要在connection.getInputStream()函数中才会真正发到服务器

                //-----------------------------POST请求-------------------------------
                connection.setDoOutput(true);//默认为false,选择POST请求必须设置为true
                connection.setDoInput(true);//默认为true,选择POST请求必须设置为true
                connection.setRequestMethod("POST");
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                String content = "id=2111&name=" + URLEncoder.encode("张三", "utf-8");
                out.writeBytes(content); //DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
                out.flush();
                out.close();

                InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    str_result += "\n" + line;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            tv_Http.setText(str_result);
        }
    }
}

你可能感兴趣的:(http,Connection,url,post,get)