使用HTTP协议访问网络 原网址https://www.2cto.com/kf/201701/552932.html

来源:互联网 发布:电子商务和软件开发 编辑:程序博客网 时间:2024/05/01 10:56

1 获取HttpURLConnection的实例:

URL url = new URL(“https://www.baidu.com”);
HttpURLConnection connection = (HttpURLConnection)url.openConnection;
2 设置请求的方法:GET POST 获取/提交
connection.setRequsestMethod(“get”);
3 自由设置
connection.setConnectionTimeout(8000);
connection.setReadTimeout(8000);
4 获取服务器返回的输入流
InputStream in = connection.getInputStream();
5 最后调用connection.disconnect();

实例:get

?
1
2
3
4
5
6
<!--?xml version="1.0"encoding="utf-8"?-->
<linearlayout android:layout_height="match_parent"android:layout_width="match_parent"android:orientation="vertical"xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"><button android:id="@+id/send_request"android:layout_height="wrap_content"android:layout_width="match_parent"android:text="Send Request">
 
    <scrollview android:layout_height="match_parent"android:layout_width="match_parent">
        <textview android:id="@+id/response_text"android:layout_height="wrap_content"android:layout_width="match_parent">
    </textview></scrollview></button></linearlayout>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
packagecom.example.networktest;
 
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.TextView;
 
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
 
publicclass MainActivity extendsAppCompatActivity implementsView.OnClickListener {
 
    publicstatic  final  int SHOW_RESPONSE = 0;
    privateButton sendRquest;
    privateTextView responseText;
    privateHandler handler = newHandler(){
        @Override
        publicvoid handleMessage(Message msg) {
           switch(msg.what) {
               caseSHOW_RESPONSE:
                   String response = (String) msg.obj;
                   //进行UI操作
                   responseText.setText(response);
           }
 
        }
    };
    @Override
    protectedvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRquest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRquest.setOnClickListener(this);
    }
 
    @Override
    publicvoid onClick(View v) {
        if(v.getId() == R.id.send_request){
            sendRequestWithHttpURLConnection();
        }
    }
 
    private void sendRequestWithHttpURLConnection(){
        //开启线程
        newThread(newRunnable() {
            @Override
            publicvoid run() {
                HttpURLConnection connection = null;
                try{
                    URL url = newURL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = newBufferedReader((newInputStreamReader(in)));
                    StringBuilder response = newStringBuilder();
                    String line ;
                    while((line = reader.readLine())!= null){
                        response.append(line);
                    }
 
                    Message message = newMessage() ;
                    message.what = SHOW_RESPONSE ;
                    message.obj = response.toString();
                    handler.sendMessage(message);
 
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    if(connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}
?
1
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

post

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
publicstatic String loginOfPost(String username, String password) {
                HttpURLConnection conn = null;
                try{
                        // 创建一个URL对象
                        URL mURL = newURL("https://192.168.0.100:8080/android/servlet/LoginServlet");
                        // 调用URL的openConnection()方法,获取HttpURLConnection对象
                        conn = (HttpURLConnection) mURL.openConnection();
 
                        conn.setRequestMethod("POST");// 设置请求方法为post
                        conn.setReadTimeout(5000);// 设置读取超时为5秒
                        conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
                        conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
 
                        // post请求的参数
                        String data = "username="+ username + "&password="+ password;
                        // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
                        OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
                        out.write(data.getBytes());
                        out.flush();// 刷新对象输出流,将任何字节都写入潜在的流中
                        out.close();
 
                        intresponseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
                        if(responseCode == 200) {
 
                                InputStream is = conn.getInputStream();
                                String state = getStringFromInputStream(is);
                                returnstate;
                        }else{
                                Log.i(TAG,"访问失败"+ responseCode);
                        }
 
                }catch(Exception e) {
                        e.printStackTrace();
                }finally{
                        if(conn != null) {
                                conn.disconnect();// 关闭连接
                        }
                }
 
                returnnull;
        }

2 使用HttpClient (在Android 6.0(API 23) 中,Google已经移除了Apache HttpClient 想关类,推荐使用HttpUrlConnection,如果要继续使用,在Android studio对应的module下的build.gradle文件中加入:
android {
useLibrary ‘org.apache.http.legacy’
})

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
packagecom.example.networktest;
 
importandroid.net.Uri;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.TextView;
 
importcom.google.android.gms.appindexing.Action;
importcom.google.android.gms.appindexing.AppIndex;
importcom.google.android.gms.common.api.GoogleApiClient;
 
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.util.EntityUtils;
 
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
 
publicclass MainActivity extendsAppCompatActivity implementsView.OnClickListener {
 
    publicstatic final int SHOW_RESPONSE = 0;
    privateButton sendRquest;
    privateTextView responseText;
    privateHandler handler = newHandler() {
        @Override
        publicvoid handleMessage(Message msg) {
            switch(msg.what) {
                caseSHOW_RESPONSE:
                    String response = (String) msg.obj;
                    //进行UI操作
                    responseText.setText(response);
            }
 
        }
    };
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    privateGoogleApiClient client;
 
    @Override
    protectedvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRquest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRquest.setOnClickListener(this);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = newGoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
 
    @Override
    publicvoid onClick(View v) {
        if(v.getId() == R.id.send_request) {
            // sendRequestWithHttpURLConnection();
            sendRequestWithHttpClient();
        }
    }
 
    privatevoid sendRequestWithHttpURLConnection() {
        //开启线程
        newThread(newRunnable() {
            @Override
            publicvoid run() {
 
                HttpURLConnection connection = null;
                try{
 
                    URL url = newURL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = newBufferedReader((newInputStreamReader(in)));
                    StringBuilder response = newStringBuilder();
                    String line;
                    while((line = reader.readLine()) != null) {
                        response.append(line);
                    }
 
                    Message message = newMessage();
                    message.what = SHOW_RESPONSE;
                    message.obj = response.toString();
                    handler.sendMessage(message);
 
                }catch(Exception e) {
                    e.printStackTrace();
                }finally{
                    if(connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
 
    privatevoid sendRequestWithHttpClient() {
        newThread(newRunnable() {
            @Override
            publicvoid run() {
                try{
                    HttpClient httpClient = newDefaultHttpClient();
                    HttpGet httpGet = newHttpGet("https://www.baidu.com");
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if(httpResponse.getStatusLine().getStatusCode() == 200){
                        HttpEntity entity =httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");
                        Message message = newMessage();
                        message.what = SHOW_RESPONSE ;
                        message.obj = response.toString();
                        handler.sendMessage(message);
                    }
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
 
    @Override
    publicvoid onStart() {
        super.onStart();
 
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW,// TODO: choose an action type.
                "Main Page",// TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("https://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.networktest/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }
 
    @Override
    publicvoid onStop() {
        super.onStop();
 
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW,// TODO: choose an action type.
                "Main Page",// TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("https://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.networktest/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}
阅读全文
0 0
原创粉丝点击