HTTP的get,post,HttpClient三种方式向服务器端提交文本数据

本文介绍在Android应用中如何使用GET、POST及HttpClient发起HTTP请求并提交数据到服务器的方法。文章详细展示了每种方法的客户端代码实现过程,包括发送XML数据、处理请求参数等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
客户端代码示例:
 
public class HttpRequest   
{     
    public static boolean sendXML(String path, String xml)throws Exception  
    {  
        byte[] data = xml.getBytes();  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setConnectTimeout(5 * 1000);  
        //如果通过post提交数据,必须设置允许对外输出数据  
        conn.setDoOutput(true);  
        conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");  
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
        OutputStream outStream = conn.getOutputStream();  
        outStream.write(data);  
        outStream.flush();  
        outStream.close();  
        if(conn.getResponseCode()==200)  
        {  
            return true;  
        }  
        return false;  
    }  
     
    public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception  
    {  
        //构造如下形式的字符串,这里的字符串依情况不同  
        // ?method=save&title=435435435&timelength=89&        
        //使用StringBuilder对象  
        StringBuilder sb = new StringBuilder(path);  
        sb.append('?');       
        //迭代Map  
        for(Map.Entry<String, String> entry : params.entrySet())  
        {  
            sb.append(entry.getKey()).append('=')  
                .append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
        }  
        sb.deleteCharAt(sb.length()-1);  
        //打开链接  
        URL url = new URL(sb.toString());  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("GET");  
        conn.setConnectTimeout(5 * 1000);  
        //如果请求响应码是200,则表示成功  
        if(conn.getResponseCode()==200)  
        {  
            return true;  
        }  
        return false;  
    }  
      
     
    public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception  
    {  
        //需要构造的字符串形式如下:  
        // title=dsfdsf&timelength=23&method=save  
        StringBuilder sb = new StringBuilder();  
        //如果参数不为空  
        if(params!=null && !params.isEmpty())  
        {  
            for(Map.Entry<String, String> entry : params.entrySet())  
            {  
                //Post方式提交参数的话,不能省略内容类型与长度  
                sb.append(entry.getKey()).append('=')  
                    .append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
            }  
            sb.deleteCharAt(sb.length()-1);  
        }  
        //得到实体的二进制数据  
        byte[] entitydata = sb.toString().getBytes();  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setConnectTimeout(5 * 1000);  
        //如果通过post提交数据,必须设置允许对外输出数据  
        conn.setDoOutput(true);  
        //这里只设置内容类型与内容长度的头字段  
        //内容类型Content-Type: application/x-www-form-urlencoded  
        //内容长度Content-Length: 38  
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
        conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));  
        OutputStream outStream = conn.getOutputStream();  
        //把实体数据写入是输出流  
        outStream.write(entitydata);  
        //内存中的数据刷入  
        outStream.flush();  
        outStream.close();  
        //如果请求响应码是200,则表示成功  
        if(conn.getResponseCode()==200)  
        {  
            return true;  
        }  
        return false;  
    }  
      
     
    public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception  
    {  
        //需要把参数放到NameValuePair  
        List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();  
        if(params!=null && !params.isEmpty())  
        {  
            for(Map.Entry<String, String> entry : params.entrySet())  
            {  
                paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
            }  
        }  
        //对请求参数进行编码,得到实体数据  
        UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);  
        //构造一个请求路径  
        HttpPost post = new HttpPost(path);   
        //设置请求实体  
        post.setEntity(entitydata);  
        //浏览器对象  
        DefaultHttpClient client = new DefaultHttpClient();   
        //执行post请求  
        HttpResponse response = client.execute(post);  
        //从状态行中获取状态码,判断响应码是否符合要求  
        if(response.getStatusLine().getStatusCode()==200)  
        {  
            return true;  
        }  
        return false;  
    }  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值