android上的http
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();