使用HTTP协议访问网络

有两种方法分别是 HttpURLConnection 和HttpClient

使用HttpURLConnection

xml界面代码:

<span style="font-size:14px;"><LinearLayout xmlns:android=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.example.networktest.MainActivity"android:orientation="vertical"><Buttonandroid:id="@+id/send_request"android:layout_height="wrap_content"android:layout_width="match_parent"android:text="Send Request"/><ScrollViewandroid:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid:id="@+id/respose_text"android:layout_width="fill_parent"android:layout_height="wrap_content"/></ScrollView></LinearLayout></span>MainActivity中的代码:

<span style="font-size:14px;">package com.example.networktest;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener {private TextView tv_response;protected static final int SHOW_RESPONSE = 0;private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case SHOW_RESPONSE:String response = (String) msg.obj;tv_response.setText(response);break;default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv_response = (TextView) findViewById(R.id.respose_text);Button btn_send = (Button) findViewById(R.id.send_request);btn_send.setOnClickListener(this);}@Overridepublic void onClick(View v) {if(v.getId()==R.id.send_request){sendRequestWithHttpURLConnection();}}private void sendRequestWithHttpURLConnection() {//开启线程发起网络请求new Thread(new Runnable() {@Overridepublic void run() {HttpURLConnection conn = null;try{URL url = new URL("?userName=dumas&passWord=1213");conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setReadTimeout(8000);conn.setConnectTimeout(8000);//对获取到的输入流进行读取InputStream is = conn.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is));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(conn!=null){conn.disconnect();}}}}).start();}}</span>注意还要添加权限:

<uses-permission android:name="android.permission.INTERNET"/>

以上是使用GET提交的,假如使用POST则如下:

<span style="font-size:14px;">private void sendRequestWithHttpURLConnection() {//开启线程发起网络请求new Thread(new Runnable() {@Overridepublic void run() {HttpURLConnection conn = null;try{URL url = new URL("");conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setReadTimeout(8000);conn.setConnectTimeout(8000);//---向服务器提交姓名和密码DataOutputStream daos = new DataOutputStream(conn.getOutputStream());daos.writeBytes("userName=duams&passWord=123");//对获取到的输入流进行读取InputStream is = conn.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is));StringBuilder response = new StringBuilder();String line;while((line= reader.readLine())!=null){response.append(line);}</span>

使用HttpClient

是用Get方式提交数据

<span style="font-size:14px;">public void run() {HttpURLConnection conn = null;try{//使用Get方式提交数据HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet("?userName=dumas&passWord=123"<span style="white-space: pre; "></span>);HttpResponse httpReponse = httpClient.execute(httpGet);if(httpReponse.getStatusLine().getStatusCode()==200){HttpEntity entity = httpReponse.getEntity();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();}finally{if(conn!=null){conn.disconnect();}}}}).start();}</span>使用POST方式提交

太过于近,彼此身上隐性的刺又会深深的伤害对方。

使用HTTP协议访问网络

相关文章:

你感兴趣的文章:

标签云: