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

android网络连接之httpclient

2016-07-14 16:17 543 查看
//get请求方式
public void dianji(View view) {
String path = "http://jsjtest.applinzi.com/one.php?name="+
+URLEncoder.encode("name")+"&pass="+"pass";
//使用HttpClient框架做get方式提交
//首先创建HttpClient客户端对象
HttpClient hc = new DefaultHttpClient();
//创建HttpGet对象
HttpGet hg = new HttpGet(path);
//使用客户端对象将get请求发送出去
try {
HttpResponse rs = hc.execute(hg);
StatusLine sl = rs.getStatusLine();
//响应头的状态行
if (sl.getStatusCode() == 200) {
//响应头的实体
HttpEntity entity = rs.getEntity();
//实体的内容是服务器输入流
InputStream is = entity.getContent();
String content = getTextFromStream(is);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//此方法读出服务器流返回的字符串
public String getTextFromStream(InputStream is) {
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
String text = new String(bos.toByteArray());
bos.close();
return text;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//post请求方式
public void dianji(View view) {
String path = "http://jsjtest.applinzi.com/one.php";
//使用HttpClient框架做post方式提交
//首先创建HttpClient客户端对象
HttpClient hc = new DefaultHttpClient();
//创建HttpPost对象
HttpPost hp = new HttpPost(path);
//设置post请求对象的实体,也就是把提交的数据封装到post请求的输出流中
BasicNameValuePair bnvp = new BasicNameValuePair("name", "名字");
BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", "密码");
List<BasicNameValuePair> list = new ArrayList<>();
list.add(bnvp);
list.add(bnvp2);
UrlEncodedFormEntity uef = null;
try {
uef = new UrlEncodedFormEntity(list, "utf-8");
hp.setEntity(uef);
HttpResponse hr = hc.execute(hp);
if(hr.getStatusLine().getStatusCode()==200){
InputStream is=hr.getEntity().getContent();
String text=getTextFromStream(is);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
//不要忘了在清单文件中写入网络权限
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: