Android网络编程:通过Http与服务器交互

Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。

如果服务器中使用Apache则Android可使用HttpClient接口

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
	android:orientation="vertical">

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:editable="false"
        android:cursorVisible="false"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="点击通过POST获取HTTP连接" />
    <ScrollView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:editable="false"
       	 	android:cursorVisible="false"/>


        
        
    </ScrollView>

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="点击通过GET获取HTTP连接" />

</LinearLayout>

package com.example.httptext;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	String urlPost = "http://115.28.143.212:8899/MyHttpSample/response.jsp";
	String urlGet = "http://www.baidu.com";
	
	Button btnPost = null;
	Button btnGET = null;
	EditText etPost = null;
	EditText etGet = null;
	String postResult = null;
	String getResult = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnPost = (Button) findViewById(R.id.button1);
		btnGET = (Button) findViewById(R.id.button2);
		etPost = (EditText) findViewById(R.id.editText2);
		etGet = (EditText) findViewById(R.id.editText1);
		btnPost.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				new Thread(){

					@Override
					public void run() {
						httpPost();
						httpGet();
						handler.sendEmptyMessage(0);
					}
					
				}.start();
				
			}
		});
	}
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			etPost.setText(postResult);
			etGet.setText(getResult);
		}
		
	};
	public void httpPost(){
		HttpPost httpPostRequest = new HttpPost(urlPost);//创建HttpPost对象
		List<NameValuePair> httpParams = new ArrayList<NameValuePair>();//创建存放参数的ArrayList
		httpParams.add(new BasicNameValuePair("name","Java"));//设置post参数
		try{
			httpPostRequest.setEntity(new UrlEncodedFormEntity(httpParams,HTTP.UTF_8));
			//创建一个DefaultHttpClient对象,并令其执行设置好的HttpPost请求。
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPostRequest);
			if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				postResult = EntityUtils.toString(httpResponse.getEntity());
				postResult = postResult.replace("\r\n|\n\r|\r|\n", "");//去掉信息中的回车和换行
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void httpGet(){
		HttpGet htttpGetRequest =new HttpGet(urlGet);
		try{
			HttpResponse httpResponse = new DefaultHttpClient().execute(htttpGetRequest);
			if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				getResult = EntityUtils.toString(httpResponse.getEntity());
				getResult = getResult.replace("\r\n|\n\r|\r|\n", "");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值