在使用Post 发送请求时,注意有一个接口org.apache.http.NameValuePair , 它有一个实现类BasicNameValuePair

一种写法是NameValuePairt namevaluePair = new BasicNameValuePair("name", name);

HttpEntity requestHttpEntity = new UrlEncodedFormEntity(namevaluePair);

HttpEntity 类既可以作为 发送请求的 请求体, 也可以作为接收响应的 响应体, 这里由于是发送Post 请求,因此定义为requestHttpEntity

下面将Get,Post 请求流程示例代码列出:

/**
* 使用 Get 发送请求
*/
HttpEntity httpEntity = null;
HttpResponse res = null;
String baseUrl = "http://192.168.1.100:8081/serverside/name";

String name = nameView.getText().toString();
String age = ageView.getText().toString();
String url = baseUrl + "?name="+name+"&age=" + age;
// 创建一个get请求对象
HttpGet httpGet = new HttpGet(url);
// 创建一个Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
InputStream is = null;
try{
res = httpClient.execute(httpGet);
httpEntity = res.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String result = "";
String line = "";
while(null != (line= reader.readLine())){
result = result + line;
}
}catch(Exception e){}


/**
* 使用 Post 发送请求
*/
HttpEntity httpEntity = null;
HttpResponse res = null;
String baseUrl = "http://192.168.1.100:8081/serverside/name";

String name = nameView.getText().toString();
String age = ageView.getText().toString();
//创建键值对 对象
NameValuePair namePair = new BasicNameValuePair("name", name);
NameValuePair agePair = new BasicNameValuePair("age", age);
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pairList.add(namePair);
pairList.add(agePair);

try{

HttpEntity requesthttpEntity = new UrlEncodedFormatEntity(pairList);
// 创建一个post请求对象
HttpPost httpPost = new HttpPost(baseUrl);
httpPost.setEntity(requesthttpEntity);
// 创建一个Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
InputStream is = null;

res = httpClient.execute(httpPost);
httpEntity = res.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String result = "";
String line = "";
while(null != (line= reader.readLine())){
result = result + line;
}

}catch(Exception e){}finally{
if (null != is)
{
is.close();
}
}


更多相关文章

  1. Android(安卓)O上获取Adaptive Icon的Bitmap对象
  2. 高德Demo,网上找了很多资料都不适合,自己研究出一个Demo,非常适合入
  3. Lync之android客户端内网登陆
  4. android中Bitmap对象怎么保存为文件?
  5. android客户端版本检测更新,服务下载,通知栏显示
  6. [Android(安卓)Pro] 关于BitmapFactory.decodeStream(is)方法无
  7. Android之Broadcast, BroadcastReceiver(广播)
  8. 关于android pendingIntent 传递Parcelable对象时数据丢失问题
  9. pull解析和json编码

随机推荐

  1. reason: HttpHostConnect Connection to
  2. android 切换到阿拉伯语电话号码+号显示
  3. android 添加音乐作为铃声
  4. Android下MP3播放器的实现源代码02
  5. android用ImageView显示网络图片
  6. Android Audio代码分析21 - 创建AudioEff
  7. Android(安卓)Audio代码分析15 - testPla
  8. Android的string.xml文件中的特殊字符显
  9. Android Studio 导入so文件
  10. Android(安卓)动态申请存储权限