方式一:HttpPost(import org.apache.http.client.methods.HttpPost
Java代码
  1. 代码如下:
  2. privateButtonbutton1,button2,button3;
  3. privateTextViewtextView1;
  4. button1.setOnClickListener(newButton.OnClickListener(){
  5. @Override
  6. publicvoidonClick(Viewarg0){
  7. //TODOAuto-generatedmethodstub
  8. //URLַ
  9. //StringuriAPI="http://www.dubblogs.cc:8751/Android/Test/API/Post/index.php";
  10. StringuriAPI="http://172.20.0.206:8082//TestServelt/login.do";
  11. /*建立HTTPPost连线*/
  12. HttpPosthttpRequest=newHttpPost(uriAPI);
  13. //Post运作传送变数必须用NameValuePair[]阵列储存
  14. //传参数服务端获取的方法为request.getParameter("name")
  15. List<NameValuePair>params=newArrayList<NameValuePair>();
  16. params.add(newBasicNameValuePair("name","thisispost"));
  17. try{
  18. //发出HTTPrequest
  19. httpRequest.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
  20. //取得HTTPresponse
  21. HttpResponsehttpResponse=newDefaultHttpClient().execute(httpRequest);
  22. //若状态码为200ok
  23. if(httpResponse.getStatusLine().getStatusCode()==200){
  24. //取出回应字串
  25. StringstrResult=EntityUtils.toString(httpResponse.getEntity());
  26. textView1.setText(strResult);
  27. }else{
  28. textView1.setText("ErrorResponse"+httpResponse.getStatusLine().toString());
  29. }
  30. }catch(ClientProtocolExceptione){
  31. textView1.setText(e.getMessage().toString());
  32. e.printStackTrace();
  33. }catch(UnsupportedEncodingExceptione){
  34. textView1.setText(e.getMessage().toString());
  35. e.printStackTrace();
  36. }catch(IOExceptione){
  37. textView1.setText(e.getMessage().toString());
  38. e.printStackTrace();
  39. }
  40. }
  41. });


方式二:HttpURLConnection、URL(import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;)
Java代码
  1. privatevoidhttpUrlConnection(){
  2. try{
  3. StringpathUrl="http://172.20.0.206:8082/TestServelt/login.do";
  4. //建立连接
  5. URLurl=newURL(pathUrl);
  6. HttpURLConnectionhttpConn=(HttpURLConnection)url.openConnection();
  7. ////设置连接属性
  8. httpConn.setDoOutput(true);//使用URL连接进行输出
  9. httpConn.setDoInput(true);//使用URL连接进行输入
  10. httpConn.setUseCaches(false);//忽略缓存
  11. httpConn.setRequestMethod("POST");//设置URL请求方法
  12. StringrequestString="客服端要以以流方式发送到服务端的数据...";
  13. //设置请求属性
  14. //获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
  15. byte[]requestStringBytes=requestString.getBytes(ENCODING_UTF_8);
  16. httpConn.setRequestProperty("Content-length",""+requestStringBytes.length);
  17. httpConn.setRequestProperty("Content-Type","application/octet-stream");
  18. httpConn.setRequestProperty("Connection","Keep-Alive");//维持长连接
  19. httpConn.setRequestProperty("Charset","UTF-8");
  20. //
  21. Stringname=URLEncoder.encode("黄武艺","utf-8");
  22. httpConn.setRequestProperty("NAME",name);
  23. //建立输出流,并写入数据
  24. OutputStreamoutputStream=httpConn.getOutputStream();
  25. outputStream.write(requestStringBytes);
  26. outputStream.close();
  27. //获得响应状态
  28. intresponseCode=httpConn.getResponseCode();
  29. if(HttpURLConnection.HTTP_OK==responseCode){//连接成功
  30. //当正确响应时处理数据
  31. StringBuffersb=newStringBuffer();
  32. StringreadLine;
  33. BufferedReaderresponseReader;
  34. //处理响应流,必须与服务器响应流输出的编码一致
  35. responseReader=newBufferedReader(newInputStreamReader(httpConn.getInputStream(),ENCODING_UTF_8));
  36. while((readLine=responseReader.readLine())!=null){
  37. sb.append(readLine).append("\n");
  38. }
  39. responseReader.close();
  40. tv.setText(sb.toString());
  41. }
  42. }catch(Exceptionex){
  43. ex.printStackTrace();
  44. }
  45. }


==================================================================================
Java代码
  1. packagealex.reader.ebook.bam;
  2. importjava.io.IOException;
  3. importjava.util.ArrayList;
  4. importjava.util.HashMap;
  5. importjava.util.Iterator;
  6. importjava.util.List;
  7. importjava.util.Map;
  8. importorg.apache.http.HttpResponse;
  9. importorg.apache.http.NameValuePair;
  10. importorg.apache.http.client.ClientProtocolException;
  11. importorg.apache.http.client.HttpClient;
  12. importorg.apache.http.client.entity.UrlEncodedFormEntity;
  13. importorg.apache.http.client.methods.HttpGet;
  14. importorg.apache.http.client.methods.HttpPost;
  15. importorg.apache.http.client.params.HttpClientParams;
  16. importorg.apache.http.impl.client.DefaultHttpClient;
  17. importorg.apache.http.message.BasicNameValuePair;
  18. importorg.apache.http.params.BasicHttpParams;
  19. importorg.apache.http.params.HttpConnectionParams;
  20. importorg.apache.http.params.HttpParams;
  21. importorg.apache.http.params.HttpProtocolParams;
  22. importorg.apache.http.protocol.HTTP;
  23. importorg.apache.http.util.EntityUtils;
  24. importandroid.app.Activity;
  25. importandroid.os.Bundle;
  26. importandroid.util.Log;
  27. importandroid.widget.EditText;
  28. publicclassSimpleClientextendsActivity{
  29. privateHttpParamshttpParams;
  30. privateHttpClienthttpClient;
  31. @Override
  32. publicvoidonCreate(BundlesavedInstanceState){
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.simple_client);
  35. EditTexteditText=(EditText)this.findViewById(R.id.EditText01);
  36. List<NameValuePair>params=newArrayList<NameValuePair>();
  37. params.add(newBasicNameValuePair("email","firewings.r@gmail.com"));
  38. params.add(newBasicNameValuePair("password","954619"));
  39. params.add(newBasicNameValuePair("remember","1"));
  40. params.add(newBasicNameValuePair("from","kx"));
  41. params.add(newBasicNameValuePair("login","登录"));
  42. params.add(newBasicNameValuePair("refcode",""));
  43. params.add(newBasicNameValuePair("refuid","0"));
  44. Mapparams2=newHashMap();
  45. params2.put("hl","zh-CN");
  46. params2.put("source","hp");
  47. params2.put("q","haha");
  48. params2.put("aq","f");
  49. params2.put("aqi","g10");
  50. params2.put("aql","");
  51. params2.put("oq","");
  52. Stringurl2="http://www.google.cn/search";
  53. Stringurl="http://wap.kaixin001.com/home/";
  54. getHttpClient();
  55. editText.setText(doPost(url,params));
  56. //editText.setText(doGet(url2,params2));
  57. }
  58. publicStringdoGet(Stringurl,Mapparams){
  59. /*建立HTTPGet对象*/
  60. StringparamStr="";
  61. Iteratoriter=params.entrySet().iterator();
  62. while(iter.hasNext()){
  63. Map.Entryentry=(Map.Entry)iter.next();
  64. Objectkey=entry.getKey();
  65. Objectval=entry.getValue();
  66. paramStr+=paramStr="&"+key+"="+val;
  67. }
  68. if(!paramStr.equals("")){
  69. paramStr=paramStr.replaceFirst("&","?");
  70. url+=paramStr;
  71. }
  72. HttpGethttpRequest=newHttpGet(url);
  73. StringstrResult="doGetError";
  74. try{
  75. /*发送请求并等待响应*/
  76. HttpResponsehttpResponse=httpClient.execute(httpRequest);
  77. /*若状态码为200ok*/
  78. if(httpResponse.getStatusLine().getStatusCode()==200){
  79. /*读返回数据*/
  80. strResult=EntityUtils.toString(httpResponse.getEntity());
  81. }else{
  82. strResult="ErrorResponse:"
  83. +httpResponse.getStatusLine().toString();
  84. }
  85. }catch(ClientProtocolExceptione){
  86. strResult=e.getMessage().toString();
  87. e.printStackTrace();
  88. }catch(IOExceptione){
  89. strResult=e.getMessage().toString();
  90. e.printStackTrace();
  91. }catch(Exceptione){
  92. strResult=e.getMessage().toString();
  93. e.printStackTrace();
  94. }
  95. Log.v("strResult",strResult);
  96. returnstrResult;
  97. }
  98. publicStringdoPost(Stringurl,List<NameValuePair>params){
  99. /*建立HTTPPost对象*/
  100. HttpPosthttpRequest=newHttpPost(url);
  101. StringstrResult="doPostError";
  102. try{
  103. /*添加请求参数到请求对象*/
  104. httpRequest.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
  105. /*发送请求并等待响应*/
  106. HttpResponsehttpResponse=httpClient.execute(httpRequest);
  107. /*若状态码为200ok*/
  108. if(httpResponse.getStatusLine().getStatusCode()==200){
  109. /*读返回数据*/
  110. strResult=EntityUtils.toString(httpResponse.getEntity());
  111. }else{
  112. strResult="ErrorResponse:"
  113. +httpResponse.getStatusLine().toString();
  114. }
  115. }catch(ClientProtocolExceptione){
  116. strResult=e.getMessage().toString();
  117. e.printStackTrace();
  118. }catch(IOExceptione){
  119. strResult=e.getMessage().toString();
  120. e.printStackTrace();
  121. }catch(Exceptione){
  122. strResult=e.getMessage().toString();
  123. e.printStackTrace();
  124. }
  125. Log.v("strResult",strResult);
  126. returnstrResult;
  127. }
  128. publicHttpClientgetHttpClient(){
  129. //创建HttpParams以用来设置HTTP参数(这一部分不是必需的)
  130. this.httpParams=newBasicHttpParams();
  131. //设置连接超时和Socket超时,以及Socket缓存大小
  132. HttpConnectionParams.setConnectionTimeout(httpParams,20*1000);
  133. HttpConnectionParams.setSoTimeout(httpParams,20*1000);
  134. HttpConnectionParams.setSocketBufferSize(httpParams,8192);
  135. //设置重定向,缺省为true
  136. HttpClientParams.setRedirecting(httpParams,true);
  137. //设置useragent
  138. StringuserAgent="Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.9.2)Gecko/20100115Firefox/3.6";
  139. HttpProtocolParams.setUserAgent(httpParams,userAgent);
  140. //创建一个HttpClient实例
  141. //注意HttpClienthttpClient=newHttpClient();是CommonsHttpClient
  142. //中的用法,在Android1.5中我们需要使用Apache的缺省实现DefaultHttpClient
  143. httpClient=newDefaultHttpClient(httpParams);
  144. returnhttpClient;
  145. }
  146. }

转载 http://blog.csdn.net/firewings_r/archive/2010/03/12/5374851.aspx

更多相关文章

  1. ANDROID图片压缩代码
  2. android 方式实现imageview圆角
  3. Android(安卓)ViewPager中嵌套Banner 导致水平滑动冲突
  4. Android(安卓)如何在Java代码中手动设置控件的marginleft
  5. Android保持屏幕常亮的方法总结
  6. Android如何使用selector设置RelativeLayout的背景
  7. Android(安卓)Glide设置图片圆角,亲测有效
  8. Android(安卓)ViewGroup系列控件的使用
  9. Android动态设置View的位置和大小

随机推荐

  1. Android 第三方库使用实例——编写.so库
  2. Android噪音检测系统
  3. 【Android】Activity Window WMS源码关系
  4. Android(安卓)IPC进程间通讯机制
  5. Android基础入门教程——8.1.2 Android中
  6. Soloπ:支付宝开源的Android专项测试工具
  7. Android中的对话框的使用技巧
  8. Android第六个功能:XmlPullParser解析XML
  9. Android(安卓)-- 基础
  10. Android代码混淆-添加了Gson遇到的问题