[教程]安卓模拟Post的提交

2014-04-23 21:00:40 -0400
package com.luoye.post;
import org.apache.http.*;
import java.util.*;
import org.apache.http.client.methods.*;
import org.apache.http.util.*;
import org.apache.http.client.entity.*;
import org.apache.http.impl.client.*;
import org.apache.http.protocol.*;

public class WebHttp
{
private String strResult;
public String Post(String path,List <NameValuePair> params)
{

HttpPost httpRequest = new HttpPost(path);
try
{
//添加请求参数到请求对象
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); //发送请求并等待响应
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200)
{
//读返回数据
strResult = EntityUtils.toString(httpResponse.getEntity());

}

}
catch (Exception e)
{
strResult="";
}
return strResult;
}
}
调用的时候:
List <NameValuePair> params = new ArrayList <NameValuePair>();
WebHttp wh=new WebHttp();
//添加要提交的表单,多个表单字段可自行添加
params.add(new BasicNameValuePair("xxxxx", "xxxxxx"));
//调用post方法
wh.Post("要post的url",params);
注:使用网络连接,请先加上联网权限并开启一个新线程。
«Newer      Older»
Comment:
Name:

Back to home

Subscribe | Register | Login | N