zoukankan      html  css  js  c++  java
  • 用HttpClient模拟HTTP的GET和POST请求(转)

    本文转自:http://blog.csdn.net/xiazdong/article/details/7724349

    一、HttpClient介绍

     
    HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器;
     
    Android已经集成了HttpClient,因此可以直接使用;
     
    注:此处HttpClient代码不只可以适用于Android,也可适用于一般的Java程序;
     
    HTTP GET核心代码:
     
    (1)DefaultHttpClient client = new DefaultHttpClient();
    (2)HttpGet get = new HttpGet(String url);//此处的URL为http://..../path?arg1=value&....argn=value
    (3)HttpResponse response = client.execute(get); //模拟请求
    (4)int code = response.getStatusLine().getStatusCode();//返回响应码
    (5)InputStream in = response.getEntity().getContent();//服务器返回的数据
     
     
    HTTP POST核心代码:
     
    (1)DefaultHttpClient client = new DefaultHttpClient();
    (2)BasicNameValuePair pair = new BasicNameValuePair(String name,String value);//创建一个请求头的字段,比如content-type,text/plain
    (3)UrlEncodedFormEntity entity = new UrlEncodedFormEntity(List<NameValuePair> list,String encoding);//对自定义请求头进行URL编码
    (4)HttpPost post = new HttpPost(String url);//此处的URL为http://..../path
    (5)post.setEntity(entity);
    (6)HttpResponse response = client.execute(post);
    (7)int code = response.getStatusLine().getStatusCode();
    (8)InputStream in = response.getEntity().getContent();//服务器返回的数据
     

    二、服务器端代码

     
    服务器端代码和通过URLConnection发出请求的代码不变:
     
    [java] view plain copy
     
    1. package org.xiazdong.servlet;  
    2.   
    3. import java.io.IOException;  
    4. import java.io.OutputStream;  
    5.   
    6. import javax.servlet.ServletException;  
    7. import javax.servlet.annotation.WebServlet;  
    8. import javax.servlet.http.HttpServlet;  
    9. import javax.servlet.http.HttpServletRequest;  
    10. import javax.servlet.http.HttpServletResponse;  
    11.   
    12. @WebServlet("/Servlet1")  
    13. public class Servlet1 extends HttpServlet {  
    14.   
    15.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    16.         String nameParameter = request.getParameter("name");  
    17.         String ageParameter = request.getParameter("age");  
    18.         String name = new String(nameParameter.getBytes("ISO-8859-1"),"UTF-8");  
    19.         String age = new String(ageParameter.getBytes("ISO-8859-1"),"UTF-8");  
    20.         System.out.println("GET");  
    21.         System.out.println("name="+name);  
    22.         System.out.println("age="+age);  
    23.         response.setCharacterEncoding("UTF-8");  
    24.         OutputStream out = response.getOutputStream();//返回数据  
    25.         out.write("GET请求成功!".getBytes("UTF-8"));  
    26.         out.close();  
    27.     }  
    28.   
    29.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    30.         request.setCharacterEncoding("UTF-8");  
    31.         String name = request.getParameter("name");  
    32.         String age  = request.getParameter("age");  
    33.         System.out.println("POST");  
    34.         System.out.println("name="+name);  
    35.         System.out.println("age="+age);  
    36.         response.setCharacterEncoding("UTF-8");  
    37.         OutputStream out = response.getOutputStream();  
    38.         out.write("POST请求成功!".getBytes("UTF-8"));  
    39.         out.close();  
    40.           
    41.     }  
    42.   
    43. }  


     

    三、Android客户端代码

     
    效果如下:
     
     
     

    在AndroidManifest.xml加入:

    [html] view plain copy
     
    1. <uses-permission android:name="android.permission.INTERNET"/>    

     
    MainActivity.java
     
    [java] view plain copy
     
    1. package org.xiazdong.network.httpclient;  
    2.   
    3. import java.io.ByteArrayOutputStream;  
    4. import java.io.IOException;  
    5. import java.io.InputStream;  
    6. import java.net.URLEncoder;  
    7. import java.util.ArrayList;  
    8. import java.util.List;  
    9.   
    10. import org.apache.http.HttpResponse;  
    11. import org.apache.http.NameValuePair;  
    12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
    13. import org.apache.http.client.methods.HttpGet;  
    14. import org.apache.http.client.methods.HttpPost;  
    15. import org.apache.http.impl.client.DefaultHttpClient;  
    16. import org.apache.http.message.BasicNameValuePair;  
    17.   
    18. import android.app.Activity;  
    19. import android.os.Bundle;  
    20. import android.view.View;  
    21. import android.view.View.OnClickListener;  
    22. import android.widget.Button;  
    23. import android.widget.EditText;  
    24. import android.widget.Toast;  
    25.   
    26. public class MainActivity extends Activity {  
    27.     private EditText name, age;  
    28.     private Button getbutton, postbutton;  
    29.     private OnClickListener listener = new OnClickListener() {  
    30.         @Override  
    31.         public void onClick(View v) {  
    32.             try{  
    33.                 if(postbutton==v){  
    34.                     /* 
    35.                      * NameValuePair代表一个HEADER,List<NameValuePair>存储全部的头字段 
    36.                      * UrlEncodedFormEntity类似于URLEncoder语句进行URL编码 
    37.                      * HttpPost类似于HTTP的POST请求 
    38.                      * client.execute()类似于发出请求,并返回Response 
    39.                      */  
    40.                     DefaultHttpClient client = new DefaultHttpClient();   //这里的DefaultHttpClient现在已经过时了,现在用的是HttpClient
    41.                     List<NameValuePair> list = new ArrayList<NameValuePair>();  
    42.                     NameValuePair pair1 = new BasicNameValuePair("name", name.getText().toString());  
    43.                     NameValuePair pair2 = new BasicNameValuePair("age", age.getText().toString());  
    44.                     list.add(pair1);  
    45.                     list.add(pair2);  
    46.                     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");  
    47.                     HttpPost post = new HttpPost("http://192.168.0.103:8080/Server/Servlet1");  
    48.                     post.setEntity(entity);  
    49.                     HttpResponse response = client.execute(post);  
    50.                       
    51.                     if(response.getStatusLine().getStatusCode()==200){  
    52.                         InputStream in = response.getEntity().getContent();//接收服务器的数据,并在Toast上显示  
    53.                         String str = readString(in);  
    54.                         Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();  
    55.                           
    56.                           
    57.                     }  
    58.                     else Toast.makeText(MainActivity.this, "POST提交失败", Toast.LENGTH_SHORT).show();  
    59.                 }  
    60.                 if(getbutton==v){  
    61.                     DefaultHttpClient client = new DefaultHttpClient();  
    62.                     StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/Servlet1");  
    63.                     buf.append("?");  
    64.                     buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");  
    65.                     buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));  
    66.                     HttpGet get = new HttpGet(buf.toString());  
    67.                     HttpResponse response = client.execute(get);  
    68.                     if(response.getStatusLine().getStatusCode()==200){  
    69.                         InputStream in = response.getEntity().getContent();  
    70.                         String str = readString(in);  
    71.                         Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();  
    72.                     }  
    73.                     else Toast.makeText(MainActivity.this, "GET提交失败", Toast.LENGTH_SHORT).show();  
    74.                 }  
    75.             }  
    76.             catch(Exception e){}  
    77.         }  
    78.     };  
    79.     @Override  
    80.     public void onCreate(Bundle savedInstanceState) {  
    81.         super.onCreate(savedInstanceState);  
    82.         setContentView(R.layout.main);  
    83.         name = (EditText) this.findViewById(R.id.name);  
    84.         age = (EditText) this.findViewById(R.id.age);  
    85.         getbutton = (Button) this.findViewById(R.id.getbutton);  
    86.         postbutton = (Button) this.findViewById(R.id.postbutton);  
    87.         getbutton.setOnClickListener(listener);  
    88.         postbutton.setOnClickListener(listener);  
    89.     }  
    90.     protected String readString(InputStream in) throws Exception {  
    91.         byte[]data = new byte[1024];  
    92.         int length = 0;  
    93.         ByteArrayOutputStream bout = new ByteArrayOutputStream();  
    94.         while((length=in.read(data))!=-1){  
    95.             bout.write(data,0,length);  
    96.         }  
    97.         return new String(bout.toByteArray(),"UTF-8");  
    98.           
    99.     }  
    100. }  
  • 相关阅读:
    无线网破解软件|一键式破解无线网|BT17软件包下载[笔记本+软件就行]
    Boost环境配置及遇到的问题解决方案
    HDU 4255 A Famous Grid
    uva 10306
    系统学习Linux的11点建议
    linux shell except tcl login ssh Automatic interaction
    常用网址记录
    am335x Qt SocketCAN Demo hacking
    a demo for how to use QThread
    OK335xS CAN device register and deiver match hacking
  • 原文地址:https://www.cnblogs.com/woaixingxing/p/6380634.html
Copyright © 2011-2022 走看看