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

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
package com.example.networktest;
 
import android.os.Handler;
import android.os.Message;
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.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
     public static  final  int SHOW_RESPONSE = 0 ;
     private Button sendRquest;
     private TextView responseText;
     private Handler handler = new Handler(){
         @Override
         public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;
                    //进行UI操作
                    responseText.setText(response);
            }
 
         }
     };
     @Override
     protected void 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
     public void onClick(View v) {
         if (v.getId() == R.id.send_request){
             sendRequestWithHttpURLConnection();
         }
     }
 
     private  void sendRequestWithHttpURLConnection(){
         //开启线程
         new Thread( new Runnable() {
             @Override
             public void run() {
                 HttpURLConnection connection = null ;
                 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();
                     BufferedReader reader = new BufferedReader(( new InputStreamReader(in)));
                     StringBuilder response = new StringBuilder();
                     String line ;
                     while ((line = reader.readLine())!= null ){
                         response.append(line);
                     }
 
                     Message message = new Message() ;
                     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
public static String loginOfPost(String username, String password) {
                 HttpURLConnection conn = null ;
                 try {
                         // 创建一个URL对象
                         URL mURL = new URL( "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();
 
                         int responseCode = conn.getResponseCode(); // 调用此方法就不必再使用conn.connect()方法
                         if (responseCode == 200 ) {
 
                                 InputStream is = conn.getInputStream();
                                 String state = getStringFromInputStream(is);
                                 return state;
                         } else {
                                 Log.i(TAG, "访问失败" + responseCode);
                         }
 
                 } catch (Exception e) {
                         e.printStackTrace();
                 } finally {
                         if (conn != null ) {
                                 conn.disconnect(); // 关闭连接
                         }
                 }
 
                 return null ;
         }

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
package com.example.networktest;
 
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
     public static final int SHOW_RESPONSE = 0 ;
     private Button sendRquest;
     private TextView responseText;
     private Handler handler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
             switch (msg.what) {
                 case SHOW_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.
      */
     private GoogleApiClient client;
 
     @Override
     protected void 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 = new GoogleApiClient.Builder( this ).addApi(AppIndex.API).build();
     }
 
     @Override
     public void onClick(View v) {
         if (v.getId() == R.id.send_request) {
             // sendRequestWithHttpURLConnection();
             sendRequestWithHttpClient();
         }
     }
 
     private void sendRequestWithHttpURLConnection() {
         //开启线程
         new Thread( new Runnable() {
             @Override
             public void run() {
 
                 HttpURLConnection connection = null ;
                 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();
                     BufferedReader reader = new BufferedReader(( new InputStreamReader(in)));
                     StringBuilder response = new StringBuilder();
                     String line;
                     while ((line = reader.readLine()) != null ) {
                         response.append(line);
                     }
 
                     Message message = new Message();
                     message.what = SHOW_RESPONSE;
                     message.obj = response.toString();
                     handler.sendMessage(message);
 
                 } catch (Exception e) {
                     e.printStackTrace();
                 } finally {
                     if (connection != null ) {
                         connection.disconnect();
                     }
                 }
             }
         }).start();
     }
 
     private void sendRequestWithHttpClient() {
         new Thread( new Runnable() {
             @Override
             public void run() {
                 try {
                     HttpClient httpClient = new DefaultHttpClient();
                     HttpGet httpGet = new HttpGet( "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 = new Message();
                         message.what = SHOW_RESPONSE ;
                         message.obj = response.toString();
                         handler.sendMessage(message);
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         }).start();
     }
 
     @Override
     public void 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
     public void 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();
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值