您的位置:首页 > 移动开发 > Android开发

Android中post和get两种方式发送请求

2014-07-02 22:05 387 查看
main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/strView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/getButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用get方法发送请求"
/>
<Button
android:id="@+id/postButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用post方法发送请求"
/>
</LinearLayout>


MainActivity.java

 

package com.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.NameValueTable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
private Button getButton = null;
private Button postButton = null;
private EditText strView = null;

private String baseUrl = "http://www.baidu.com/s?";

private HttpResponse httpResponse = null;//响应对象
private HttpEntity httpEntity = null;//取出响应内容的消息对象
InputStream inputStream = null;//输入流对象

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

strView = (EditText) findViewById(R.id.strView);
getButton = (Button) findViewById(R.id.getButton);
postButton = (Button) findViewById(R.id.postButton);

//get方法发送请求
getButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str = strView.getText().toString();
String url = baseUrl + "?wd=" + str;

//生成一个请求对象
HttpGet httpGet = new HttpGet(url);
//生成一个http客户端对象
HttpClient httpClient = new DefaultHttpClient();
//发送请求
try {
httpResponse = httpClient.execute(httpGet);//接收响应
httpEntity = httpResponse.getEntity();//取出响应
//客户端收到响应的信息流
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{//最后一定要关闭输入流
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

});

//post方法发送请求
postButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str = strView.getText().toString();//参数
NameValuePair nameValuePair = new BasicNameValuePair("content", str);//键值对
//然后将键值对放到列表里(类似于形成数组)
//List是一个接口,而ListArray是一个类。ListArray继承并实现了List。所以List不能被构造,但可以向上面那样为List创建一个引用,而ListArray就可以被构造。
//List list = new ArrayList();这句创建了一个ArrayList的对象后把上溯到了List。此时它是一个List对象了
//而ArrayList list=new ArrayList();创建一对象则保留了ArrayList的所有属性。
//为什么一般都使用 List list = new ArrayList() ,而不用 ArrayList alist = new ArrayList()呢? 问题就在于List有多个实现类,如 LinkedList或者Vector等等,现在你用的是ArrayList,也许哪一天你需要换成其它的实现类呢?,这时你只要改变这一行就行了:List list = new LinkedList(); 其它使用了list地方的代码根本不需要改动。
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(nameValuePair);//将键值对放入到列表中
try {
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs);//对参数进行编码操作
//生成一个post请求对象
HttpPost httpPost = new HttpPost(baseUrl);
httpPost.setEntity(requestHttpEntity);
//生成一个http客户端对象
HttpClient httpClient = new DefaultHttpClient();//发送请求
try {
httpResponse = httpClient.execute(httpPost);//接收响应
httpEntity = httpResponse.getEntity();//取出响应
//客户端收到响应的信息流
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{//最后一定要关闭输入流
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

});
}
}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.http"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>


 

 

注意的几点哦:

1.get方式的参数是加在url后面的,而post方式是讲参数先放到键值对对象中,然后将键值对相添加到list列表里,然后讲列表放到信息里进行发送

2.http请求发送需要连网,故AndroidManifest.xml中要加上<uses-permission android:name="android.permission.INTERNET" />连网权限

3.获得消息的时候要创建文本输入流,结束时一定要关闭输入流。

 try{

                            inputStream.close();

                        }catch(Exception e){

                            e.printStackTrace();

                        }

 暂时就这些吧。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: