您的位置:首页 > 理论基础 > 计算机网络

Android 网络编程

2014-04-28 15:04 441 查看
,在JAVA中进行网络通信,我们需要定义一个HttpPost对象,此对象需要输入url参数。然后定义一个List<NameValuePair>对象来以JSON的形式存储数据。接着通过HttpPost的getParams().setParameter()方法进行一些必要参数的设置,例如连接超时的时间与接收数据超时的时间。然后通过HttpResponse httpResponse = new DefaultHttpClient().execute(request); 语句来发送Http请求并获取服务器端传来的数据。此时的数据为String类型,需要吧它转换成JSONObject,以便后面的分析数据与获取我们需要的数据。

网络通讯关键代码:

HttpPost   request = new HttpPost(url);

List<NameValuePair>   params = new   ArrayList<NameValuePair>();

params.add(new   BasicNameValuePair("username","I am username"

);

params.add(new   BasicNameValuePair("password", "I am password");

params.add(new   BasicNameValuePair("verName", verName));

request.getParams().setParameter(

CoreConnectionPNames.CONNECTION_TIMEOUT,   10000);

request.getParams().setParameter(   CoreConnectionPNames.SO_TIMEOUT, 10000);

request.setEntity(new UrlEncodedFormEntity(params,   HTTP.UTF_8));

HttpResponse   httpResponse = new   DefaultHttpClient() .execute(request);

String retSrc   = EntityUtils.toString(httpResponse .getEntity());

JSONObject   result = new   JSONObject(retSrc);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: