Adroid调用API接口返回Json类型数据

package com.contentprovide.liuliu.number;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by liuliu on 2018/1/5.
 */
//定义一个发送消息的类,并接受到返回的json数据
public class HttpUtils {

    private static final String tourl = "http://apis.juhe.cn/mobile/get";//发送消息去的地方的地址


    public static String DoGet(String msg) {

        String result = "";
        InputStream is;
        ByteArrayOutputStream baos;

        String url = setParams(msg);//得到完整url
        try {
            URL urlNet = new URL(url);//发送url请求

            HttpURLConnection conn = (HttpURLConnection) urlNet.openConnection();
//            给conn设置参数
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");//设置请求方式
//拿到服务器返回的InputStream
            is = conn.getInputStream();
//            将从服务器获得的流is转换为字符串
            int len = -1;//初始值,起标志位作用
            byte buf[] = new byte[128];//缓冲区
            baos = new ByteArrayOutputStream();//捕获内存缓冲区的数据转换为字节数组
            while ((len = is.read(buf)) != -1) {//循环读取内容,将输入流的内容放进缓冲区中
                baos.write(buf, 0, len);//将缓冲区内容写进输出流
            }
            result = new String(baos.toByteArray());//最终结果


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    //定义方法为url设置参数
    public static String setParams(String msg) {
        String url = "http://apis.juhe.cn/mobile/get?phone=" + msg + "&dtype=json&key=72a24be15b8b58c599d4d2f994e26cdb";
        return url;
    }


}

 

posted @ 2018-01-09 15:21  西红柿里没有番茄  阅读(327)  评论(0编辑  收藏  举报