您的位置:首页 > Web前端 > JavaScript

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

2016-04-24 20:09 656 查看
//新建这个类,在需要的时候通过类名点方法名+你要请求数据的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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: