Android Studio访问Http资源之HttpURLConnection的案例(GET方式)

默认已经有服务器(自己本地搭建的或远程的),没有的可以拿个免费接口先来用用,随便一搜就有的。

这里使用的url是http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手机号

xml文件就不放了,只有Button。

public class MainActivity extends AppCompatActivity {
     

    private Button btn1;
    

    private String urlAddressFront = "http://tcc.taobao.com";
    private String urlAddressMethod = "/cc/json/mobile_tel_segment.htm";

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

        btn1 = (Button) findViewById(R.id.btn_get);

        btn1.setOnClickListener(new View.OnClickListener() {
     
    	    @Override
    	    public void onClick(View v) {
     
                doGet("168********");   //手机号
    	    }
	});

    }

    //doGet请求
    private void doGet(String s) {
     
        final String urlAddress = urlAddressFront + urlAddressMethod + "?tel=" + s ;     //拼接出完整的url

        new Thread(new Runnable() {
                  //开启一个异步线程,AS在3.0后不允许在主线程中访问网络
            @Override
            public void run() {
     
                try {
     
                    URL url = new URL(urlAddress);              //URL对象
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();     //生成HttpURLConnection对象
                    httpURLConnection.connect();            //连接服务器

                    //服务器响应
                    if (httpURLConnection.getResponseCode() == 200){
             //服务器响应码
                        InputStream inputStream = httpURLConnection.getInputStream();       //输入流
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));     //BufferedReader构造方法
                        StringBuffer stringBuffer = new StringBuffer();     //用来存储读的结果
                        String readLine = "";       //存储每行的结果
                        while ((readLine = bufferedReader.readLine()) != null){
          //按行读取,每行读到的字符串放到readLine中
                            stringBuffer.append(readLine);
                            inputStream.close();
                            bufferedReader.close();
                            httpURLConnection.disconnect();
                            Log.d("TAG",stringBuffer.toString());
                        }
                    }else {
     
                        Log.d("TAG","failed");
                    }
                } catch (MalformedURLException e) {
     
                    e.printStackTrace();
                } catch (IOException e) {
     
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

你可能感兴趣的:(android,android,studio,http,网络通信)