android http协议post请求方式
方式一: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请求方式的更多相关文章
- Android——JDK的get请求方式
layout文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:an ...
- http协议----->http请求方式,post,get
4.http请求方式有七种(http请求是想web资源请求数据) Post get head options delete trace put 常用:GET POST POST例如form表单提交,G ...
- android post带数据请求方式,传递的数据格式包括json和map
如下: public static String httpPost(String url, String json) { try { URL u = new URL(url); HttpURLConn ...
- JAVAEE 和项目开发(第三课:HTTP的请求头和请求方式)
HTTP 协议之请求格式 请求格式的结构:请求行:请求方式.请求的地址和 HTTP 协议版本 请求头:消息报头,一般用来说明客户端要使用的一些附加信息 空行: 位于请求行和请求数据之间,空行是必须 ...
- Android通过http协议POST传输方式
Android通过http协议POST传输方式如下: 方式一:HttpPost(import org.apache.http.client.methods.HttpPost) 代码如下: privat ...
- Android之Http通信——3.Android HTTP请求方式:HttpURLConnection
3.Android HTTP请求方式之HttpURLConnection 引言: 好了,前两节我们已经对HTTP协议进行了学习.相信看完前两节的朋友对HTTP协议相比之前 应该更加熟悉吧.好吧.学了要 ...
- android中用get和post方式向服务器提交请求
通过get和post方式向服务器发送请求首先说一下get和post的区别get请求方式是将提交的参数拼接在url地址后面,例如http://www.baidu.com/index.jsp?num=23 ...
- Android进阶(一)几种网络请求方式详解
Ref:http://blog.csdn.net/zuolongsnail/article/details/6373051 Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面 ...
- Android Volley框架的几种post提交请求方式
首先简单描述一下Google的Android开发团队在2013年推出的一个网络通信框架Volley.它的设计目标是进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如下载文件等,Vol ...
随机推荐
- eclipse 32位和64位的jre
让32位Eclipse和64位Eclipse同是在64的Windows7上运行 用文本编辑器打开eclipse.ini文件,在-vmargs之前加入下面的内容: -vm C:\Program Fil ...
- Machine Learning—Mixtures of Gaussians and the EM algorithm
印象笔记同步分享:Machine Learning-Mixtures of Gaussians and the EM algorithm
- redis-2.6.16源码分析之pub-sub系统
redis实现的发送订阅系统,即pub-sub,这部分的的代码比较少,也方便分析.在这只将会分析下普通的pub-sub(会忽略掉Pattern-matching subscriptions),以此来简 ...
- 更改Zend Studio/Eclipse代码风格主题
最近决定把几个IDE的代码样式统一一下,Visual Studio的还算好改,PHP目前用得不多,不过也打算给Zend Studio换身新装. 网上搜索的一些更改Zend Studio主题的多是修改或 ...
- struts2,hibernate,spring整合笔记(4)--struts与spring的整合
饭要一口一口吃,程序也要一步一步写, 很多看起来很复杂的东西最初都是很简单的 下面要整合struts和spring spring就是我们的管家,原来我们费事费神的问题统统扔给她就好了 先写一个测试方法 ...
- wildcard
[rusky@rhel7 test]$ lstest1 test123 test2 test317 test33 test335 test336 test44 testtest[rus ...
- 检查主机是否存活的shell脚本
#!/bin/bash PREFIX= num= " ]; do echo -en "Pinging ${PREFIX}.${num}..." >& &qu ...
- nginx配置学习文章
partOne 自我释义部分 我的是阿里云的ubuntu *******实际上感觉这里是基本配置,很用不到*********#定义其用户或用户组user www-data;#nginx的进程数,应当为 ...
- ComboBox相关操作
取组合框文本示例: 1 void ShowDlgWage::OnCbnSelendokCombo1() { // TODO: 在此添加控件通知处理程序代码 CString str; int i; i ...
- php单例模式在数据库连接中的使用
今天同事问到一个关于单例模式在php中是否有用的问题,我们知道,单例的目的是为了避免重复生产相同的对象,一般情况在数据库连接中,为了避免多次拿到相同数据库连接,使用到单例模式,我们来看一下单例模式数据 ...