现在的位置: 首页 > 综合 > 正文

android http协议post请求方式

2017年10月14日 ⁄ 综合 ⁄ 共 10388字 ⁄ 字号 评论关闭

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

Java代码  收藏代码
  1. 代码如下:  
  2.   
  3. private Button button1,button2,button3;  
  4. private TextView textView1;  
  5.   
  6. button1.setOnClickListener(new Button.OnClickListener(){           
  7.    @Override  
  8.    public void onClick(View arg0) {  
  9.     // TODO Auto-generated method stub  
  10.     //URLַ  
  11. //     String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Post/index.php";  
  12.      String uriAPI = "http://172.20.0.206:8082//TestServelt/login.do";  
  13.     /*建立HTTP Post连线*/  
  14.     HttpPost httpRequest =new HttpPost(uriAPI);  
  15.     //Post运作传送变数必须用NameValuePair[]阵列储存  
  16.     //传参数 服务端获取的方法为request.getParameter("name")  
  17.     List <NameValuePair> params=new ArrayList<NameValuePair>();  
  18.     params.add(new BasicNameValuePair("name","this is post"));  
  19.     try{  
  20.        
  21.        
  22.      //发出HTTP request  
  23.      httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  24.      //取得HTTP response  
  25.      HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);  
  26.        
  27.      //若状态码为200 ok   
  28.      if(httpResponse.getStatusLine().getStatusCode()==200){  
  29.       //取出回应字串  
  30.       String strResult=EntityUtils.toString(httpResponse.getEntity());  
  31.       textView1.setText(strResult);  
  32.      }else{  
  33.       textView1.setText("Error Response"+httpResponse.getStatusLine().toString());  
  34.      }  
  35.     }catch(ClientProtocolException e){  
  36.      textView1.setText(e.getMessage().toString());  
  37.      e.printStackTrace();  
  38.     } catch (UnsupportedEncodingException e) {  
  39.      textView1.setText(e.getMessage().toString());  
  40.      e.printStackTrace();  
  41.     } catch (IOException e) {  
  42.      textView1.setText(e.getMessage().toString());  
  43.      e.printStackTrace();  
  44.     }  
  45.    }  
  46.            
  47.         });  



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

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



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

Java代码  收藏代码
  1. package alex.reader.ebook.bam;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import org.apache.http.HttpResponse;  
  11. import org.apache.http.NameValuePair;  
  12. import org.apache.http.client.ClientProtocolException;  
  13. import org.apache.http.client.HttpClient;  
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  15. import org.apache.http.client.methods.HttpGet;  
  16. import org.apache.http.client.methods.HttpPost;  
  17. import org.apache.http.client.params.HttpClientParams;  
  18. import org.apache.http.impl.client.DefaultHttpClient;  
  19. import org.apache.http.message.BasicNameValuePair;  
  20. import org.apache.http.params.BasicHttpParams;  
  21. import org.apache.http.params.HttpConnectionParams;  
  22. import org.apache.http.params.HttpParams;  
  23. import org.apache.http.params.HttpProtocolParams;  
  24. import org.apache.http.protocol.HTTP;  
  25. import org.apache.http.util.EntityUtils;  
  26.   
  27. import android.app.Activity;  
  28. import android.os.Bundle;  
  29. import android.util.Log;  
  30. import android.widget.EditText;  
  31.   
  32. public class SimpleClient extends Activity {  
  33.   
  34.     private HttpParams httpParams;  
  35.   
  36.     private HttpClient httpClient;  
  37.   
  38.     @Override  
  39.     public void onCreate(Bundle savedInstanceState) {  
  40.         super.onCreate(savedInstanceState);  
  41.         setContentView(R.layout.simple_client);  
  42.   
  43.         EditText editText = (EditText) this.findViewById(R.id.EditText01);  
  44.   
  45.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  46.         params.add(new BasicNameValuePair("email""firewings.r@gmail.com"));  
  47.         params.add(new BasicNameValuePair("password""954619"));  
  48.         params.add(new BasicNameValuePair("remember""1"));  
  49.         params.add(new BasicNameValuePair("from""kx"));  
  50.         params.add(new BasicNameValuePair("login""登 录"));  
  51.         params.add(new BasicNameValuePair("refcode"""));  
  52.         params.add(new BasicNameValuePair("refuid""0"));  
  53.   
  54.         Map params2 = new HashMap();  
  55.   
  56.         params2.put("hl""zh-CN");  
  57.   
  58.         params2.put("source""hp");  
  59.   
  60.         params2.put("q""haha");  
  61.   
  62.         params2.put("aq""f");  
  63.   
  64.         params2.put("aqi""g10");  
  65.   
  66.         params2.put("aql""");  
  67.   
  68.         params2.put("oq""");  
  69.   
  70.         String url2 = "http://www.google.cn/search";  
  71.   
  72.         String url = "http://wap.kaixin001.com/home/";  
  73.   
  74.         getHttpClient();  
  75.   
  76.         editText.setText(doPost(url, params));  
  77.   
  78.         // editText.setText(doGet(url2, params2));  
  79.   
  80.     }  
  81.   
  82.     public String doGet(String url, Map params) {  
  83.   
  84.         /* 建立HTTPGet对象 */  
  85.   
  86.         String paramStr = "";  
  87.   
  88.         Iterator iter = params.entrySet().iterator();  
  89.         while (iter.hasNext()) {  
  90.             Map.Entry entry = (Map.Entry) iter.next();  
  91.             Object key = entry.getKey();  
  92.             Object val = entry.getValue();  
  93.             paramStr += paramStr = "&" + key + "=" + val;  
  94.         }  
  95.   
  96.         if (!paramStr.equals("")) {  
  97.             paramStr = paramStr.replaceFirst("&""?");  
  98.             url += paramStr;  
  99.         }  
  100.         HttpGet httpRequest = new HttpGet(url);  
  101.   
  102.         String strResult = "doGetError";  
  103.   
  104.         try {  
  105.   
  106.             /* 发送请求并等待响应 */  
  107.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  108.             /* 若状态码为200 ok */  
  109.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  110.                 /* 读返回数据 */  
  111.                 strResult = EntityUtils.toString(httpResponse.getEntity());  
  112.   
  113.             } else {  
  114.                 strResult = "Error Response: "  
  115.                         + httpResponse.getStatusLine().toString();  
  116.             }  
  117.         } catch (ClientProtocolException e) {  
  118.             strResult = e.getMessage().toString();  
  119.             e.printStackTrace();  
  120.         } catch (IOException e) {  
  121.             strResult = e.getMessage().toString();  
  122.             e.printStackTrace();  
  123.         } catch (Exception e) {  
  124.             strResult = e.getMessage().toString();  
  125.             e.printStackTrace();  
  126.         }  
  127.   
  128.         Log.v("strResult", strResult);  
  129.   
  130.         return strResult;  
  131.     }  
  132.   
  133.     public String doPost(String url, List<NameValuePair> params) {  
  134.   
  135.         /* 建立HTTPPost对象 */  
  136.         HttpPost httpRequest = new HttpPost(url);  
  137.   
  138.         String strResult = "doPostError";  
  139.   
  140.         try {  
  141.             /* 添加请求参数到请求对象 */  
  142.             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  143.             /* 发送请求并等待响应 */  
  144.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  145.             /* 若状态码为200 ok */  
  146.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  147.                 /* 读返回数据 */  
  148.                 strResult = EntityUtils.toString(httpResponse.getEntity());  
  149.   
  150.             } else {  
  151.                 strResult = "Error Response: "  
  152.                         + httpResponse.getStatusLine().toString();  
  153.             }  
  154.         } catch (ClientProtocolException e) {  
  155.             strResult = e.getMessage().toString();  
  156.             e.printStackTrace();  
  157.         } catch (IOException e) {  
  158.             strResult = e.getMessage().toString();  
  159.             e.printStackTrace();  
  160.         } catch (Exception e) {  
  161.             strResult = e.getMessage().toString();  
  162.             e.printStackTrace();  
  163.         }  
  164.   
  165.         Log.v("strResult", strResult);  
  166.   
  167.         return strResult;  
  168.     }  
  169.   
  170.     public HttpClient getHttpClient() {  
  171.   
  172.         // 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的)  
  173.   
  174.         this.httpParams = new BasicHttpParams();  
  175.   
  176.         // 设置连接超时和 Socket 超时,以及 Socket 缓存大小  
  177.   
  178.         HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);  
  179.   
  180.         HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);  
  181.   
  182.         HttpConnectionParams.setSocketBufferSize(httpParams, 8192);  
  183.   
  184.         // 设置重定向,缺省为 true  
  185.   
  186.         HttpClientParams.setRedirecting(httpParams, true);  
  187.   
  188.         // 设置 user agent  
  189.   
  190.         String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";  
  191.         HttpProtocolParams.setUserAgent(httpParams, userAgent);  
  192.   
  193.         // 创建一个 HttpClient 实例  
  194.   
  195.         // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient  
  196.   
  197.         // 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient  
  198.   
  199.         httpClient = new DefaultHttpClient(httpParams);  
  200.   
  201.         return httpClient;  
  202.     }  
  203. }  


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

抱歉!评论已关闭.