android网络连接之httpclient

//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();
    }

}
//不要忘了在清单文件中写入网络权限
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值