亲爱的!直接建此类传一个URL即可得到json串非常方便

//新建这个类,在需要的时候通过类名点方法名+你要请求数据的URL调用里面的getstring()方法,返回的就是一个json串用字符串接一下就直接可以用json解析了


get方法:

public class FenLei {

    public static String getString(String uri){
        HttpClient http=new DefaultHttpClient();
        HttpGet httpGet=new HttpGet(uri);
        try {
            HttpResponse response=http.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                String string = EntityUtils.toString(entity,"utf-8");
                return string;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}


post方法

   
            //获得网络客户端
            HttpClient client=new DefaultHttpClient();
            //获得Post网络方法
            HttpPost post=new HttpPost(uri);
            //post的进行传参,NameValuePair名称值对,在http下有这样一个类
            List<NameValuePair> list=new ArrayList<NameValuePair>();
            //BasicNameValuePair表基本名称值对,前者表示=前的值,后者表示=后的值
            list.add(new BasicNameValuePair("key","c56a18e43d8bdea60a341c5e80ade5d1"));
            try {
                //为网络设置实体内容
                post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
               //客户端Httpclient开始执行网络post请求,得到网络请求
                HttpResponse response = client.execute(post);
                //通过网络请求获得状态行的状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println(statusCode);
                //判断状态码是否等于200,如果等于200,则证明状态为连接
                if(statusCode==200){
                    //得到请求实体内容的输入流
                    InputStream is = response.getEntity().getContent();
                    //实例化一输出流,将读到的内容通过输出流写入的客户端
                    ByteArrayOutputStream baos=new ByteArrayOutputStream();
                    //定义一个字节
                    byte[] b=new byte[1024];
                    //定义一个长度
                    int len;
                    //循环将读到的内容通过输出流写入的客户端
                    while((len=is.read(b))!=-1){
                        baos.write(b, 0, len);
                    }
                    json = baos.toString();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值