andriod 中的 GET ,POST 请求方式

本文详细介绍了在Android平台下利用HTTP客户端(如DefaultHttpClient)和URL连接(如HttpURLConnection)两种方式执行HTTP POST请求的方法,并通过实例展示了如何构造请求参数、设置请求头以及处理响应。

一、HttpClinet方式

1、HTTP GET 示例:

public class TestHttpGetMethod{  
    public void get(){  
        BufferedReader in = null;  
        try{  
            HttpClient client = new DefaultHttpClient();  
            HttpGet request = new HttpGet();  
            request.setURI("http://w26.javaeye.com");  
            HttpResponse response = client.execute(request);   
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));     
            StringBuffer sb = new StringBuffer("");   
            String line = "";  
            String NL = System.getProperty("line.separator");  
            while((line = in.readLine()) != null){  
                sb.append(line + NL); 

            }  
            in.close();  
            String page = sb.toString();  
            Log.i(TAG, page);  
        }catch(Exception e){  
            Log.e(TAG,e.toString())  
        }finally{  
            if(in != null){  
                try{  
                    in.close();  
                }catch(IOException ioe){  
                    Log.e(TAG, ioe.toString());  
                }  
            }  
        }  
    }  
}


2、HTTP POST 示例:

public class TestHttpPostMethod{  
    public void post(){  
        BufferedReader in = null;  
        try{  
            HttpClient client = new DefaultHttpClient();  
            HttpPost request = new HttpPost("http://localhost/upload.jsp");   
            List<NameValuePair> postParams = new ArrayList<NameValuePair>();  
            postParams.add(new BasicNameValuePair("filename", "sex.mov"));  
            UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);  
            request.setEntity(formEntity);  
            HttpResponse response = client.execute(request);  
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));     
            StringBuffer sb = new StringBuffer("");   
            String line = "";  
            String NL = System.getProperty("line.separator");  
            while((line = in.readLine()) != null){  
                sb.append(line + NL);  
            }  
            in.close();  
            String result = sb.toString();  
            Log.i(TAG, result );  
        }catch(Exception e){  
            Log.e(TAG,e.toString())  
        }finally{  
            if(in != null){  
                try{  
                    in.close();  
                }catch(IOException ioe){  
                    Log.e(TAG, ioe.toString());  
                }  
            }  
        }  
    } 
}


二、HttpURLConnection 方式


URL url = null;
HttpURLConnection conn = null;
InputStream in = null;
OutputStream out = null;
byte[] data ="测试字符串".getBytes();
try{
   url =new URL("www.xxx.com/servlet");
   conn = (HttpURLConnection) url.openConnection();

   //设置连接属性
   conn.setDoOutput(true);// 使用 URL 连接进行输出
   conn.setDoInput(true);// 使用 URL 连接进行输入
   conn.setUseCaches(false);// 忽略缓存
   conn.setConnectTimeout(30000);//设置连接超时时长,单位毫秒
   conn.setRequestMethod("POST");//设置请求方式,POST or GET,注意:如果请求地址为一个servlet地址的话必须设置成POST方式

//设置请求头
  conn.setRequestProperty("Accept", "*/*");
  conn.setRequestProperty("Connection", "Keep-Alive");
  conn.setRequestProperty("Accept-Charset", "utf-8");
  if (data != null) {
     out = conn.getOutputStream();
     out.write(data);
  }
  int code = conn.getResponseCode();
  if(code ==200){
     in = conn.getInputStream();// 可能造成阻塞
     long len = conn.getContentLength();
     byte[] bs = new byte[(int) len];//返回结果字节数组
     int all = 0;
  int dn = 0;
     while ((dn = in.read(bs, all, 1)) > 0) {
       all += dn;
       if (all == len) {
       break;
       }
     }
  }
}

那么接下来让我们看看在Android平台开发中如何执行一个Post请求:


package com.jixuzou.search;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class mian extends Activity {
        /** Called when the activity is first created. */
        private Button btnTest;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                btnTest = (Button) findViewById(R.id.Button01);
                btnTest.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                getWeather();
                        }
                });
        }
        private void getWeather(){
                try {
                        final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址
                        HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求
                        List params = new ArrayList();
                        params.add(new BasicNameValuePair("theCityCode", "长沙")); // 添加必须的参数
                        params.add(new BasicNameValuePair("theUserID", "")); // 添加必须的参数
                        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数的编码
                        HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈
// 解析返回的内容
                        if (httpResponse.getStatusLine().getStatusCode() != 404)
                        {
                                String result = EntityUtils.toString(httpResponse.getEntity());
                                System.out.println(result);
                        }
                } catch (Exception e) {
                }
        }
}



【SCI复现】含可再生能源与储能的区域微电网最优运行:应对不确定性的解鲁棒性与非预见性研究(Matlab代码实现)内容概要:本文围绕含可再生能源与储能的区域微电网最优运行展开研究,重点探讨应对不确定性的解鲁棒性与非预见性策略,通过Matlab代码实现SCI论文复现。研究涵盖多阶段鲁棒调度模型、机会约束规划、需求响应机制及储能系统优化配置,结合风电、光伏等可再生能源出力的不确定性建模,提出兼顾系统经济性与鲁棒性的优化运行方案。文中详细展示了模型构建、算法设计(如C&CG算法、大M法)及仿真验证全过程,适用于微电网能量管理、电力系统优化调度等领域的科研与工程实践。; 适合人群:具备一定电力系统、优化理论和Matlab编程基础的研究生、科研人员及从事微电网、能源管理相关工作的工程技术人员。; 使用场景及目标:①复现SCI级微电网鲁棒优化研究成果,掌握应对风光负荷不确定性的建模与求解方法;②深入理解两阶段鲁棒优化、分布鲁棒优化、机会约束规划等先进优化方法在能源系统中的实际应用;③为撰写高水平学术论文或开展相关课题研究提供代码参考和技术支持。; 阅读建议:建议读者结合文档提供的Matlab代码逐模块学习,重点关注不确定性建模、鲁棒优化模型构建与求解流程,并尝试在不同场景下调试与扩展代码,以深化对微电网优化运行机制的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值