android上面有两种通讯代码:
第一种是用java.net和java.io包来搞
第二种用apache的开源项目,而android就集成了apache的开源项目,所以推荐使用这个


先说说基于apache的开源项目的:

HttpPost post = new HttpPost(urlStr);
//有一个httpPost对象,这个对象可以绑定参数------setEntity()
比如:可以绑定一个json对象的string

JSONObject holder = new JSONObject();
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
StringEntity se = new StringEntity(holder.toString());

或者是一个list
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("s_username", strUID));
nvps.add(new BasicNameValuePair("s_password", strUPW));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

把要发送的信息准备好后,可以发送了,这要用到发送的客户端
DefaultHttpClient client = new DefaultHttpClient();

执行发送命令并返回结果
HttpResponse resp = client.execute(post);

得到实例:
HttpEntity entity = resp.getEntity();

获得inputStream
InputStream is = httpEntity.getContent();

Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
iv.setImageBitmap(bitmap);


BufferedReader br =
new BufferedReader(new InputStreamReader(entity.getContent()));
循环拿出string

或者:最好是用apache 的 s = EntityUtils.toString(entity);

然后说:基于原始的java.io包----
URL url =new URL(urlStr); HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=****");
con.setRequestProperty("type", "txt");
con.setRequestProperty("name", "e");
//相当于设置了一个HttpPost

DataOutputStream ds =
new DataOutputStream(con.getOutputStream()); //准备输出数据

/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(uploadFile);

/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];

int length = -1;
/* 从文件读取数据至缓冲区 */
while((length = fStream.read(buffer)) != -1)
{
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length); //在输出流里面写数据
}

/* close streams */
fStream.close();
ds.flush();








更多相关文章

  1. android中使用sqlite、复制assets下的数据库到SD卡、支持大于1M
  2. Android网络收音机项目
  3. 2015Android设备、系统、分辨率最新统计数据
  4. 2010-03-02 传智播客—Android(四)数据存储之五网络
  5. 22、从头学Android之Android的数据存储--SQLite
  6. Android入门篇五:使用全局变量在Activity之间传递数据
  7. 3.4 管理项目 - 创建Android库
  8. 第十二章:Android数据存储(下)

随机推荐

  1. 解析MySQL中存储时间日期类型的选择问题
  2. Mysql主从同步Last_IO_Errno:1236错误解
  3. MySQL优化之使用连接(join)代替子查询
  4. MYSQL子查询和嵌套查询优化实例解析
  5. 浅谈mysql的子查询联合与in的效率
  6. mysql in语句子查询效率慢的优化技巧示例
  7. MySQL批量去掉某个字段中的空格
  8. 企业生产MySQL优化介绍
  9. mysql数据库开发规范【推荐】
  10. MySQL表排序规则不同错误问题分析