您的位置:首页 > 理论基础 > 计算机网络

Android网络技术之HttpURLConnection

2017-04-07 09:20 417 查看
        不得不说,安卓开发者们还是很幸运的。

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

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

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

[b]int getResponseCode()                                        获取服务器的响应代码 ,           [/b]

[b]String[b]getResponseMessage()                             获取发送请求的方法,[/b][/b]

[b][b]String [b]get[/b]RequestMethod()                                  获取发送请求的方法 ,               [/b][/b]

[b]void set[b]RequestMethod(String method)             获取发送请求的方法。[/b][/b]

例子:

<?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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息