HttpClient 连接网络的两种方法doGet和doPost

本文详细介绍了Android中使用HttpClient进行GET和POST请求的方法,并展示了如何与AsyncTask结合实现异步网络请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        大家都知道android连接网络有两种方式,一种是HttpClient,另一种是HttpURLConnection,下面就先把我自己学习的第一种连网方式HttpClient记录下来,后一种方法有空再记录下来,好记心始终不如烂笔头啊。

       android连网分HttpClient和HttpURLConnection两种,而HttpClient又分doGet和doPost两种,HttpURLConnection也分doGet和doPost两种;

     一,不管是什么方式连网,都要检查网络的可用性

ConnectivityManager cm = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		if (info != null) {
			Toast.makeText(HttpClientAsyncTaskActivity.this,
					"连网正常" + info.getTypeName(), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(HttpClientAsyncTaskActivity.this, "未连网",
					Toast.LENGTH_SHORT).show();
		}

在写这段代码前一定要先加权限:

    
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class HttpClientActivity extends Activity implements OnClickListener {
	private TextView mTextView, mTextView1;
	private Button mButton, mButton1, mButton2,mButton3;
	private EditText mEditText;
	private ProgressDialog pq;
	private String addressurl = "http://192.168.1.196:8080/WebRoot/dogetServlet?name=admins&password=1234";
	// private String addressurl = "http://www.baidu.com";

	private String addressurl1 = "http://192.168.1.196:8080/WebRoot/dogetServlet";

	/**
	 * 一get方法 通过get方法获取服务器数据的两个方式HttpClient,HttpURLConnection
	 * 传参直接在地址url中加上"?name=admins&password=1234" 传递的参数直接显示出来,不安全
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http_layout);

		mTextView = (TextView) findViewById(R.id.httpclient_text);
		mTextView1 = (TextView) findViewById(R.id.httpurl_text);
		mButton = (Button) findViewById(R.id.http_httpclient_get_but);
		mButton.setOnClickListener(this);
		mButton1 = (Button) findViewById(R.id.http_httclient_post_but);
		mButton1.setOnClickListener(this);
		mButton2 = (Button) findViewById(R.id.http_httpurl_get_but);
		mButton2.setOnClickListener(this);
		mButton3=(Button) findViewById(R.id.http_httpurl_post_but);
		mButton3.setOnClickListener(this);
		mEditText=(EditText) findViewById(R.id.httpurl_edit);
	}

doPost方法:

/**
	 * @param HttpClient POST请求
	 */
	public String getContentByHttpClientByPost(String httpurl) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(httpurl);
			/** POST组装参数 **/
			BasicNameValuePair userNamePair = new BasicNameValuePair("name",
					"露西");
			BasicNameValuePair passWordPair = new BasicNameValuePair(
					"password", "abcd");
			ArrayList<BasicNameValuePair> Pairlist = new ArrayList<BasicNameValuePair>();
			Pairlist.add(userNamePair);
			Pairlist.add(passWordPair);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Pairlist,
					HTTP.UTF_8);
			httpPost.setEntity(entity);
			httpPost.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=utf-8");

			HttpResponse response = httpclient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			Log.d("HttpClient  POST", "statusCode>>>>>>>: " + statusCode);
			if (statusCode == HttpURLConnection.HTTP_OK) {
				String content = EntityUtils.toString(response.getEntity());
				Log.d("HttpClient  POST", "content>>>>>>>>: " + content);
				return content;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

由于连接网络属于耗时操作,要实现HttpClient通信必须与AsyncTask异步机制结合,AsyncTask异步机制其实就是把线程和Handler消息机制封装的方法,当然这是系统封装好的的类;

case R.id.http_httclient_post_but:

			new AsyncTask<String, Void, String>() {// 实现HttpClient通信与AsyncTask异步机制的结合
				protected String doInBackground(String... params) {
					String url = params[0];

					return getContentByHttpClientByPost(url);
				}

				protected void onPostExecute(String result) {

					if (result != null) {
						mTextView.setText(result);
						Log.v("HttpClient  POST", "onPostExecute>>post:"
								+ result);
					}

				}
			}.execute(addressurl1);
			break;


 

doGet方法:

/**
	 * 
	 * HttpClient GET请求
	 * 
	 */
	public String getContentByHttpClient(String httpurl) {
		InputStream in = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();// 实例化HttpClient类
			HttpGet httpGet = new HttpGet(httpurl);// 用get方法请求
			HttpResponse response = httpClient.execute(httpGet);// 执行get请求方法返回
																// response

			int statusCode = response.getStatusLine().getStatusCode();// 通过获取状态行再获取状态码
			Log.v("", "statusCode>>>>>:" + statusCode);

			if (statusCode == HttpURLConnection.HTTP_OK) {// statusCode==200isok

				in = response.getEntity().getContent();// 获取信息内容

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in, "UTF-8"));
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				Log.v("", "sb.toString():" + sb.toString());
				return sb.toString();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
同样,doGet方法也要与异步机制一起使用:
<pre class="java" name="code">case R.id.http_httpclient_get_but:
			/** 参数组装 **/
			// String urls="http://192.168.1.196:8080/WebRoot/dogetServlet";
			// String parameter="?name=admins&password=1234";
			// String urlss=urls+parameter;
			// Log.v("","url>>>>:"+urlss);

			new AsyncTask<String, Void, String>() {// 实现HttpClient通信与AsyncTask异步机制的结合
				protected String doInBackground(String... params) {
					String url = params[0];

					return getContentByHttpClient(url);
				}

				protected void onPostExecute(String result) {

					if (result != null) {
						mTextView.setText(result);
						// pq.dismiss();// 消除dialog
						Log.v("", "onPostExecute:" + result);
					}

				}
			}.execute(addressurl);
			// pq = ProgressDialog.show(this, "请稍后。。。", "正在请求数据");
			break;


权限配置:
<pre class="html" name="code">  <uses-permission android:name="android.permission.INTERNET" />









                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值