Android网络技术之HttpURLConnection

        不得不说,安卓开发者们还是很幸运的。

        为咋?以前HTTP协议不是有两种方式来访问网络吗,分别是HttpURLConnection和HttpClient,HttpClient的功能在Android6.0系统中被完全删除。

        HttpURLConnection继承自URLConnection,因此也可以用于向指定网站发送GET(表示希望从服务器那里获取数据)、POST(表示希望提交数据给服务器)请求。

        HttpURLConnectionURLConnection的基础上做了一些改进,增加了一些用于操作HTTP资源的便捷方法。

int getResponseCode()                                        获取服务器的响应代码 ,           

StringgetResponseMessage()                             获取发送请求的方法,

String getRequestMethod()                                  获取发送请求的方法 ,               

void setRequestMethod(String method)             获取发送请求的方法。

例子:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/http_button" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/http_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>
package com.xhm.demo.providertestling;

import android.app.Activity;
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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionActivity extends Activity {
    TextView httpText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_urlconnection);
        Button httpButton=(Button) findViewById(R.id.http_button);
        httpText=(TextView) findViewById(R.id.http_text);
        httpButton.setOnClickListener(httpButtonHttpURLConnection);
    }
    View.OnClickListener httpButtonHttpURLConnection=
            new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpURLConnection connection=null;
                    BufferedReader reader=null;
                    try {
                        //获取到HttpURLConnection的实例,一般只需new
                        //出一个URL对象,并传入目标的网络地址
                        URL url=new URL("https://www.baidu.com/");
                        //然后调用一下openConnection()方法
                        connection=(HttpURLConnection) url.openConnection();
                        //设置HTTP请求所使用的方法,
                        connection.setRequestMethod("GET");
                        //进行一些自由的定制操作,比如:设置连接超时、
                        // 读取超时的毫秒数等
                        connection.setConnectTimeout(8000);
                        connection.setReadTimeout(8000);
                        //调用getInputStream()方法获取到服务器返回的输入流
                        InputStream in=connection.getInputStream();
                        //下面对获取的输入流进行读取
                        reader=new BufferedReader(new InputStreamReader(in));
                        StringBuilder response=new StringBuilder();
                        String line;
                        while ((line=reader.readLine())!=null){
                            response.append(line);
                        }
                        showResponse(response.toString());
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        if (reader!=null){
                            try {
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (connection!=null){
                            //关闭连接
                            connection.disconnect();
                        }
                    }
                }
            }).start();
        }
    };
    private void showResponse(final String response){
        //将线程切换到主线程
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                httpText.setText(response);
            }
        });
    }
}

        “POST”方法怎么用呢?POST是提交数据的,那么在获取输入流之前把要提交的数据写出即可,注意一下数据都是以键值的形式存在,数据与数据之间用“&”隔开。

connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("name=android&password=123456");

IDstart1110636277IDendOpenstart9011829155178214OpenendBannerstart9071427185570273BannerendInterstitialstart6061921175375235Interstitialend

{"appid":"1110636277","splash":"9011829155178214","banner":"9071427185570273","screen":"6061921175375235","market":{"ali":"1","baidu":"1","huawei":"1","kuan":"1","oppo":"1","qq":"1","samsung":"1","dev360":"1","vivo":"1","xiaomi":"1"}}

一、Json文件的编写规则
1.文件中的不同对象都需要用{ };
2.每个对象都需要用“ ”,相应对象的值:若是文本则用“”,若是数值则直接写;
3.若某对象下又有很多其他不同的子对象,则这些子对象需要整体用{ };
4.若某对象下有很多可选的相同名称的成员,这些成员需要用[ ],可理解为数组,事实上读取文件代码就按数组处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值