Android Http Get/Post 传递参数 Demo

来源:互联网 发布:淘宝店铺经营管理 编辑:程序博客网 时间:2024/04/28 11:09


             在Android中,所集成的HttpClient并非常见的Jakarta CommonsHttpClient 3.x (org.apache.commons.httpclient.* package)而是HttpClent 4.0 org.apache.http.×

            Demo:

                         设计两个Button ,分别发出 get 和post 请求,并通过TextView显示内容。

                         注意点:1.在android2.3之后 在主线程中必须使用另一个线程  如handler机制,或者异步任务获取网络数据

                                              如果非得在主线程中操作,可以使用:Android平台中(Android 2.3起),新增加了一个新的类,叫                                                 StrictMode(android.os.StrictMode)。这个类可以用来帮助开发者改进他们编写的应用,并且提供了各种的策略,这些策                           略能随时检查和报告开发者开发应用中存在的问题,比如可以监视那些本不应该在主线程中完成的工作或者其他的一些不规                           范和不好的代码。开发中感觉这种方式不佳。

                     2.在Mainifest中加入权限。

主类代码Demo:

package com.dong.mytest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView);
//为了解决网络异常
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
public void usePost(View v){
String uriAPI ="http://www.baidu.com/s";
HttpPost httpRequest = new HttpPost(uriAPI);//Create Post connection
//Post must use Array of NameValuePair[] to delay variables.
List<NameValuePair> params = new ArrayList<NameValuePair>() ;
params.add(new BasicNameValuePair("wd", "android"));

try {
//Send Http request
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// get HttpResponse
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
//Judge state
if(httpResponse.getStatusLine().getStatusCode() == 200){
String temp = EntityUtils.toString(httpResponse.getEntity());
tv.setText(temp);
} else {
tv.setText("Error Response:"+httpResponse.getStatusLine());
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tv.setText(e.getMessage().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tv.setText(e.getMessage().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tv.setText(e.getMessage().toString());
}


}
public void useGet(View v){

String uriAPI ="http://www.baidu.com/s?wd=安卓";
//Create HttpRequest
HttpGet httpRequGet =new HttpGet(uriAPI);
try {
//Get response
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequGet);

if(httpResponse.getStatusLine().getStatusCode() == 200){
String temp = EntityUtils.toString(httpResponse.getEntity());

tv.setText(temp);
} else {
tv.setText("Error Response:"+httpResponse.getStatusLine());
}

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block\
tv.setText(e.getMessage().toString());
e.printStackTrace();
} catch (IOException e) {
tv.setText(e.getMessage().toString());
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


        

0 0
原创粉丝点击