HttpClient模拟HTTP的GET和POST请求

本文详细介绍了如何在Android应用中利用Apache HttpClient库实现与服务器的GET和POST请求交互,包括请求参数的编码、服务器端的响应处理以及客户端如何接收并展示服务器返回的数据。

一、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] 
package org.xiazdong.servlet; 
 
import java.io.IOException; 
import java.io.OutputStream; 
 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
@WebServlet("/Servlet1") 
public class Servlet1 extends HttpServlet { 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        String nameParameter = request.getParameter("name"); 
        String ageParameter = request.getParameter("age"); 
        String name = new String(nameParameter.getBytes("ISO-8859-1"),"UTF-8"); 
        String age = new String(ageParameter.getBytes("ISO-8859-1"),"UTF-8"); 
        System.out.println("GET"); 
        System.out.println("name="+name); 
        System.out.println("age="+age); 
        response.setCharacterEncoding("UTF-8"); 
        OutputStream out = response.getOutputStream();//返回数据 
        out.write("GET请求成功!".getBytes("UTF-8")); 
        out.close(); 
    } 
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        request.setCharacterEncoding("UTF-8"); 
        String name = request.getParameter("name"); 
        String age  = request.getParameter("age"); 
        System.out.println("POST"); 
        System.out.println("name="+name); 
        System.out.println("age="+age); 
        response.setCharacterEncoding("UTF-8"); 
        OutputStream out = response.getOutputStream(); 
        out.write("POST请求成功!".getBytes("UTF-8")); 
        out.close(); 
         
    } 
 

 

三、Android客户端代码

效果如下:

 


在AndroidManifest.xml加入:

[html
<uses-permission android:name="android.permission.INTERNET"/>   


MainActivity.java

[java] 
package org.xiazdong.network.httpclient; 
 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URLEncoder; 
import java.util.ArrayList; 
import java.util.List; 
 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
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.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 
 
public class MainActivity extends Activity { 
    private EditText name, age; 
    private Button getbutton, postbutton; 
    private OnClickListener listener = new OnClickListener() { 
        @Override 
        public void onClick(View v) { 
            try{ 
                if(postbutton==v){ 
                    /*
                     * NameValuePair代表一个HEADER,List<NameValuePair>存储全部的头字段
                     * UrlEncodedFormEntity类似于URLEncoder语句进行URL编码
                     * HttpPost类似于HTTP的POST请求
                     * client.execute()类似于发出请求,并返回Response
                     */ 
                    DefaultHttpClient client = new DefaultHttpClient(); 
                    List<NameValuePair> list = new ArrayList<NameValuePair>(); 
                    NameValuePair pair1 = new BasicNameValuePair("name", name.getText().toString()); 
                    NameValuePair pair2 = new BasicNameValuePair("age", age.getText().toString()); 
                    list.add(pair1); 
                    list.add(pair2); 
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8"); 
                    HttpPost post = new HttpPost("http://192.168.0.103:8080/Server/Servlet1"); 
                    post.setEntity(entity); 
                    HttpResponse response = client.execute(post); 
                     
                    if(response.getStatusLine().getStatusCode()==200){ 
                        InputStream in = response.getEntity().getContent();//接收服务器的数据,并在Toast上显示 
                        String str = readString(in); 
                        Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); 
                         
                         
                    } 
                    else Toast.makeText(MainActivity.this, "POST提交失败", Toast.LENGTH_SHORT).show(); 
                } 
                if(getbutton==v){ 
                    DefaultHttpClient client = new DefaultHttpClient(); 
                    StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/Servlet1"); 
                    buf.append("?"); 
                    buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&"); 
                    buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8")); 
                    HttpGet get = new HttpGet(buf.toString()); 
                    HttpResponse response = client.execute(get); 
                    if(response.getStatusLine().getStatusCode()==200){ 
                        InputStream in = response.getEntity().getContent(); 
                        String str = readString(in); 
                        Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); 
                    } 
                    else Toast.makeText(MainActivity.this, "GET提交失败", Toast.LENGTH_SHORT).show(); 
                } 
            } 
            catch(Exception e){} 
        } 
    }; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        name = (EditText) this.findViewById(R.id.name); 
        age = (EditText) this.findViewById(R.id.age); 
        getbutton = (Button) this.findViewById(R.id.getbutton); 
        postbutton = (Button) this.findViewById(R.id.postbutton); 
        getbutton.setOnClickListener(listener); 
        postbutton.setOnClickListener(listener); 
    } 
    protected String readString(InputStream in) throws Exception { 
        byte[]data = new byte[1024]; 
        int length = 0; 
        ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
        while((length=in.read(data))!=-1){ 
            bout.write(data,0,length); 
        } 
        return new String(bout.toByteArray(),"UTF-8"); 
         
    } 

作者:xiazdong

先展示下效果 https://pan.quark.cn/s/a4b39357ea24 遗传算法 - 简书 遗传算法的理论是根据达尔文进化论而设计出来的算法: 人类是朝着好的方向(最优解)进化,进化过程中,会自动选择优良基因,淘汰劣等基因。 遗传算法(英语:genetic algorithm (GA) )是计算数学中用于解决最佳化的搜索算法,是进化算法的一种。 进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择、杂交等。 搜索算法的共同特征为: 首先组成一组候选解 依据某些适应性条件测算这些候选解的适应度 根据适应度保留某些候选解,放弃其他候选解 对保留的候选解进行某些操作,生成新的候选解 遗传算法流程 遗传算法的一般步骤 my_fitness函数 评估每条染色体所对应个体的适应度 升序排列适应度评估值,选出 前 parent_number 个 个体作为 待选 parent 种群(适应度函数的值越小越好) 从 待选 parent 种群 中随机选择 2 个个体作为父方和母方。 抽取父母双方的染色体,进行交叉,产生 2 个子代。 (交叉概率) 对子代(parent + 生成的 child)的染色体进行变异。 (变异概率) 重复3,4,5步骤,直到新种群(parentnumber + childnumber)的产生。 循环以上步骤直至找到满意的解。 名词解释 交叉概率:两个个体进行交配的概率。 例如,交配概率为0.8,则80%的“夫妻”会生育后代。 变异概率:所有的基因中发生变异的占总体的比例。 GA函数 适应度函数 适应度函数由解决的问题决定。 举一个平方和的例子。 简单的平方和问题 求函数的最小值,其中每个变量的取值区间都是 [-1, ...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值