关于HttpURLConnection的用法

时间:2022-04-20 05:12:08
package com.example.fafa.mydemoaboutnet;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mBtn;
    private TextView mViewText;
    private Button mSend;


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

    private void iniView() {
        mBtn = (Button) findViewById(R.id.my_btn);
        mViewText = (TextView) findViewById(R.id.view_text);
        mSend = (Button) findViewById(R.id.btn_send);
        mSend.setOnClickListener(this);
        mBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_btn:
                getMessages();//服务器端获取数据
                break;
            case R.id.btn_send:
                sendMessages();//客户端发送数据比如用户名密码之类的
                break;
        }

    }

    private void sendMessages() {
        new Thread(new Runnable() {
            HttpURLConnection connection=null;
            BufferedReader mreader=null;//这一步写在外面不然finally无法处理
            @Override
            public void run() {
                try {
                    URL url= new URL("http://192.168.191.1:8080/bigweb/tologin");
                    connection= ((HttpURLConnection) url.openConnection());
                    connection.setRequestMethod("POST");
                    DataOutputStream out =new DataOutputStream(connection.getOutputStream());
                    out.writeBytes("username=yang&password=123456");
                    //post请求  在这里我是用的朋友的阿帕奇上的一个登陆的模块 判断我传递过去的数据 然后返回给我一个字符串
                    //结果接受成功
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    String line;
                    mreader=new BufferedReader(new InputStreamReader(in));
                    StringBuilder response= new StringBuilder();
                    while((line=mreader.readLine())!=null){
                        response.append(line);
                    }
                    showView(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(mreader==null){
                        try {
                            mreader.close();//你请求的网址如果不正确 这里会报错
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void getMessages() {
        new Thread(new Runnable() {
            HttpURLConnection connection=null;
            BufferedReader mreader=null;//这一步写在外面不然finally无法处理
            @Override
            public void run() {
                try {
                    URL url= new URL("https://www.baidu.com");
                    connection= ((HttpURLConnection) url.openConnection());//获取实例传入目标地址
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    mreader=new BufferedReader(new InputStreamReader(in));
                    String line;
                    StringBuilder response= new StringBuilder();
                    while((line=mreader.readLine())!=null){
                        response.append(line);
                    }
                    showView(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(mreader==null){
                        try {
                            mreader.close();//你请求的网址如果不正确 这里会报错
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showView(final String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //这里进行了 UI操作子线程是不能更新UI的 需要用handler 但是这里的runOnUiRhread是可以的
                //因为它本身就是进行了handler的 点进去你会发现他进行的是一个senddelaymessage操作
                mViewText.setText(s);
            }
        });
    }
}
以上是代码 XML就不贴出来了 XML就是二个按钮 一个是发送数据 一个是接受数据  还有一个ScrollView
里面存放一个TextView用来显示服务器端返回的数据