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

Http访问网络(AsyncTask 异步加载和使用HttpURLConnection)

2015-07-30 19:36 681 查看
两种方式访问百度,并且将服务器所传回的值设置在TextView中。用AsyncTask来实现

一、HttpURLConnection

步骤:

URL url = new URL("http://www.baidu.com");

HttpURLConnection connection = url.openConnection();

//此处connection可设置请求方式和连接超时、读取超时的秒数

//connection.setRequestMethod("GET")

InputStream in = connection.getInputStream();

//可以根据输入流来读取数据

connection.disconnnect();

如果想给服务器提交数据:需要将requestedMethod改为POST,并且再获取输入流执之前将要提交的数据写出即可

每条数据以键值对方式存在,数据与数据之间用&隔开

connection.setRequestMethod("POST");

DataOutputStream out = new DataOutputStream("connection.getOutputStream()");

out.writeBytes("username=admin&passwd=123456");

二、HttpClient的方式:

HttpClient是一个接口,因此无法创建它的实例,一般通过DefaultHttpClient来创建实例

步骤:

HttpClient httpClient = new DefaultHttpClient();

//如果发起GET请求

HttpGet httpGet = new HttpGet("http://www.baidu.com");

HttpResponse response =httpClient.execute(httpGet);

执行execute 方法之后,会返回一个HttpResponse对象,服务器返回的信息就会包含在这里面

取服务器返回的状态码,如果等于200,则说明请求和响应都成功了

if(resonse.getStatusLine().getStatusCode()==200){

//首先获得HttpEntity对象

HttpEntity entity = response.getEntity();

//EntityUtils.toString得到最终的结果

String result = EntityUtils.toString(entity,"utf-8");

}

但是,如果是POST请求,则比GET请求稍微麻烦一点

httpPost-->NameValuePair-->BasicNameValuePair--->UrlEncodedFormEntity--->setEntity

//如果发起POST请求

HttpPost httpPost = new HttpPost("http://www.baidu.com");

//通过NameValuePair来存放待提交的数据

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("username","admin"));

params.add(new BasicNameValurPair("passwd","123"));

//将得到的参数集合传到UrlEncodedFromEntity

UrlEncodedFormEntity entity= new UrlEncodedFormEntity(params,"utf-8");

httpPost.setEntity(entity);

之后的步骤就和GET一样 httpClient.execute(httpPost);

BUT,当我在Android studio中基于API 22开发时,会发现用HttpClient ,编译器会提示deprecated,也就是不赞成或者有更好的替代,所以不推荐用HttpClient

布局:

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

</ScrollView>


用HttpURLConnection代码:

String url="http://www.baidu.com"
TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView)findViewById(R.id.text);

new MyAsyncTask().execute(url);
}
//传进去的是String类型的url地址,想得到服务器返回的数据
class MyAsyncTask extends AsyncTask<String,Void,String>{

@Override
protected String doInBackground(String... params) {
return getDataFromUrl(params[0]);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mTextView.setText(s);
}
}
//根据Url获得输入流,之后解析成String类型的数据
public String getDataFromUrl(String url)  {
HttpURLConnection connection;
InputStream is = null;
String result = "";
String line ="";
try {
URL url1 = new URL(url);
connection = (HttpURLConnection) url1.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=bufferedReader.readLine())!=null){
result +=line;
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: