方式一:HttpPost(import org.apache.http.client.methods.HttpPost

代码如下:

private Button button1,button2,button3;
private TextView textView1; button1.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//URLַ
// String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Post/index.php";
String uriAPI = "http://172.20.0.206:8082//TestServelt/login.do";
/*建立HTTP Post连线*/
HttpPost httpRequest =new HttpPost(uriAPI);
//Post运作传送变数必须用NameValuePair[]阵列储存
//传参数 服务端获取的方法为request.getParameter("name")
List <NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name","this is post"));
try{ //发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//取得HTTP response
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest); //若状态码为200 ok
if(httpResponse.getStatusLine().getStatusCode()==){
//取出回应字串
String strResult=EntityUtils.toString(httpResponse.getEntity());
textView1.setText(strResult);
}else{
textView1.setText("Error Response"+httpResponse.getStatusLine().toString());
}
}catch(ClientProtocolException e){
textView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
textView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (IOException e) {
textView1.setText(e.getMessage().toString());
e.printStackTrace();
}
} });

方式二:HttpURLConnection、URL(import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;)

    private void httpUrlConnection(){
try{
String pathUrl = "http://172.20.0.206:8082/TestServelt/login.do";
//建立连接
URL url=new URL(pathUrl);
HttpURLConnection httpConn=(HttpURLConnection)url.openConnection(); ////设置连接属性
httpConn.setDoOutput(true);//使用 URL 连接进行输出
httpConn.setDoInput(true);//使用 URL 连接进行输入
httpConn.setUseCaches(false);//忽略缓存
httpConn.setRequestMethod("POST");//设置URL请求方法
String requestString = "客服端要以以流方式发送到服务端的数据..."; //设置请求属性
//获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
byte[] requestStringBytes = requestString.getBytes(ENCODING_UTF_8);
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
httpConn.setRequestProperty("Content-Type", "application/octet-stream");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset", "UTF-8");
//
String name=URLEncoder.encode("黄武艺","utf-8");
httpConn.setRequestProperty("NAME", name); //建立输出流,并写入数据
OutputStream outputStream = httpConn.getOutputStream();
outputStream.write(requestStringBytes);
outputStream.close();
//获得响应状态
int responseCode = httpConn.getResponseCode();
if(HttpURLConnection.HTTP_OK == responseCode){//连接成功 //当正确响应时处理数据
StringBuffer sb = new StringBuffer();
String readLine;
BufferedReader responseReader;
//处理响应流,必须与服务器响应流输出的编码一致
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), ENCODING_UTF_8));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
tv.setText(sb.toString());
}
}catch(Exception ex){
ex.printStackTrace();
}
}

==================================================================================

    package alex.reader.ebook.bam;  

    import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; 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.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText; public class SimpleClient extends Activity { private HttpParams httpParams; private HttpClient httpClient; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_client); EditText editText = (EditText) this.findViewById(R.id.EditText01); List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", "firewings.r@gmail.com"));
params.add(new BasicNameValuePair("password", ""));
params.add(new BasicNameValuePair("remember", ""));
params.add(new BasicNameValuePair("from", "kx"));
params.add(new BasicNameValuePair("login", "登 录"));
params.add(new BasicNameValuePair("refcode", ""));
params.add(new BasicNameValuePair("refuid", "")); Map params2 = new HashMap(); params2.put("hl", "zh-CN"); params2.put("source", "hp"); params2.put("q", "haha"); params2.put("aq", "f"); params2.put("aqi", "g10"); params2.put("aql", ""); params2.put("oq", ""); String url2 = "http://www.google.cn/search"; String url = "http://wap.kaixin001.com/home/"; getHttpClient(); editText.setText(doPost(url, params)); // editText.setText(doGet(url2, params2)); } public String doGet(String url, Map params) { /* 建立HTTPGet对象 */ String paramStr = ""; Iterator iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
paramStr += paramStr = "&" + key + "=" + val;
} if (!paramStr.equals("")) {
paramStr = paramStr.replaceFirst("&", "?");
url += paramStr;
}
HttpGet httpRequest = new HttpGet(url); String strResult = "doGetError"; try { /* 发送请求并等待响应 */
HttpResponse httpResponse = httpClient.execute(httpRequest);
/* 若状态码为200 ok */
if (httpResponse.getStatusLine().getStatusCode() == ) {
/* 读返回数据 */
strResult = EntityUtils.toString(httpResponse.getEntity()); } else {
strResult = "Error Response: "
+ httpResponse.getStatusLine().toString();
}
} catch (ClientProtocolException e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} catch (IOException e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} catch (Exception e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} Log.v("strResult", strResult); return strResult;
} public String doPost(String url, List<NameValuePair> params) { /* 建立HTTPPost对象 */
HttpPost httpRequest = new HttpPost(url); String strResult = "doPostError"; try {
/* 添加请求参数到请求对象 */
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* 发送请求并等待响应 */
HttpResponse httpResponse = httpClient.execute(httpRequest);
/* 若状态码为200 ok */
if (httpResponse.getStatusLine().getStatusCode() == ) {
/* 读返回数据 */
strResult = EntityUtils.toString(httpResponse.getEntity()); } else {
strResult = "Error Response: "
+ httpResponse.getStatusLine().toString();
}
} catch (ClientProtocolException e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} catch (IOException e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} catch (Exception e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} Log.v("strResult", strResult); return strResult;
} public HttpClient getHttpClient() { // 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的) this.httpParams = new BasicHttpParams(); // 设置连接超时和 Socket 超时,以及 Socket 缓存大小 HttpConnectionParams.setConnectionTimeout(httpParams, * ); HttpConnectionParams.setSoTimeout(httpParams, * ); HttpConnectionParams.setSocketBufferSize(httpParams, ); // 设置重定向,缺省为 true HttpClientParams.setRedirecting(httpParams, true); // 设置 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
HttpProtocolParams.setUserAgent(httpParams, userAgent); // 创建一个 HttpClient 实例 // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient // 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); return httpClient;
}
}

android http协议post请求方式的更多相关文章

  1. Android——JDK的get请求方式

    layout文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:an ...

  2. http协议----->http请求方式,post,get

    4.http请求方式有七种(http请求是想web资源请求数据) Post get head options delete trace put 常用:GET POST POST例如form表单提交,G ...

  3. android post带数据请求方式,传递的数据格式包括json和map

    如下: public static String httpPost(String url, String json) { try { URL u = new URL(url); HttpURLConn ...

  4. JAVAEE 和项目开发(第三课:HTTP的请求头和请求方式)

    HTTP 协议之请求格式   请求格式的结构:请求行:请求方式.请求的地址和 HTTP 协议版本 请求头:消息报头,一般用来说明客户端要使用的一些附加信息 空行: 位于请求行和请求数据之间,空行是必须 ...

  5. Android通过http协议POST传输方式

    Android通过http协议POST传输方式如下: 方式一:HttpPost(import org.apache.http.client.methods.HttpPost) 代码如下: privat ...

  6. Android之Http通信——3.Android HTTP请求方式:HttpURLConnection

    3.Android HTTP请求方式之HttpURLConnection 引言: 好了,前两节我们已经对HTTP协议进行了学习.相信看完前两节的朋友对HTTP协议相比之前 应该更加熟悉吧.好吧.学了要 ...

  7. android中用get和post方式向服务器提交请求

    通过get和post方式向服务器发送请求首先说一下get和post的区别get请求方式是将提交的参数拼接在url地址后面,例如http://www.baidu.com/index.jsp?num=23 ...

  8. Android进阶(一)几种网络请求方式详解

    Ref:http://blog.csdn.net/zuolongsnail/article/details/6373051 Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面 ...

  9. Android Volley框架的几种post提交请求方式

    首先简单描述一下Google的Android开发团队在2013年推出的一个网络通信框架Volley.它的设计目标是进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如下载文件等,Vol ...

随机推荐

  1. 总结工作中常用到的linux命令大全_经典

    常用解压命令 tar.bz2 命令: tar -jxvf  *.tar.bz2 tar.z   命令: tar -zxvf  *.tar.z tar.gz   命令: tar -Zxvf  *.tar ...

  2. 使用CCUserDefault 推断用户是否是第一次登陆系统及UserDefault全路径的获取

    bool bfirst =CCUserDefault::sharedUserDefault()->getBoolForKey("first"); //假设不能获取该键值,创建 ...

  3. linux内核--中断处理程序

    一个设备的中断处理程序是它设备驱动程序的一部分--设备驱动程序是用于对设备进行管理的内核代码.中断处理程序与其他内核函数的真正区别在于,中断处理程序是被内核调用来响应中断的,而它们运行于我们称之为中断 ...

  4. 传入字典的模型项的类型为“System.Data.Entity.DynamicProxies.

    今天做东西遇到了,这样的一个问题,最后了半天才找到问题所在,现在给大家分享一下问题所在: 传入字典的模型项的类型为“System.Data.Entity.DynamicProxies.doctorUs ...

  5. Dev GridControl 按条件合并相同单元格

    Dev 默认的合并方式,只要(垂直方向)相邻两个单元格的值相同都会进行合并,这种方式并不是最优的,所以需要在进行合并的过程中进行判断. 方式如下: 1:先设置需要合并的列为允许合并 OptionsVi ...

  6. call和apply区别

    call和apply 基本上是一个意思 区别在于call的第二个参数可以是任意的类型,而apply的第二个参数必须是数组,也可以是arguments.call方法:语法:call(thisObj,Ob ...

  7. python运行时间计算之timeit

    timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000) stmt:statement ...

  8. js接收复选框的值

    <td><input type="checkbox" class="title" name="title" value=& ...

  9. 【转】Multithreaded Python Tutorial with the “Threadworms” Demo

    The code for this tutorial can be downloaded here: threadworms.py or from GitHub. This code works wi ...

  10. SQL存储过程+游标 循环批量()操作数据

    本人收集的,挺有用的 1. 利用游标循环更新.删除MemberAccount表中的数据 DECLARE My_Cursor CURSOR --定义游标 FOR (SELECT * FROM dbo.M ...