中国和世界天气全能版 API接受到的json字符串为空 求大神解决

拾荒者101 2016-03-01 07:56:54
package com.example.dell_.weather;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

String httpUrl = "http://apis.baidu.com/heweather/pro/attractions";
String httpArg = "cityid=CN10101010018A";

public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;

try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "63768771fba86cb8f45097013d35074e");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
protected void onStart() {
super.onStart();
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String jsonResult = request(httpUrl, httpArg);
Log.i("test","1111"+jsonResult);
}
});
}
}
...全文
199 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
tony4geek 2016-03-02
  • 打赏
  • 举报
回复
Intboy 2016-03-02
  • 打赏
  • 举报
回复

工具测试结果正常。
结果数据如下:

{
"HeWeather data service 3.0": [
{
"basic": {
"city": "故宫博物院",
"cnty": "中国",
"id": "CN10101010018A",
"lat": "116.39",
"lon": "39.91",
"update": {
"loc": "2016-03-02 10:10",
"utc": "2016-03-02 02:10"
}
},
"daily_forecast": [
{
"astro": {
"sr": "06:45",
"ss": "18:07"
},
"cond": {
"code_d": "101",
"code_n": "101",
"txt_d": "多云",
"txt_n": "多云"
},
"date": "2016-03-02",
"tmp": {
"max": "17",
"min": "3"
},
"wind": {
"dir": "南风",
"sc": "微风"
}
},
{
"astro": {
"sr": "06:44",
"ss": "18:08"
},
"cond": {
"code_d": "101",
"code_n": "305",
"txt_d": "多云",
"txt_n": "小雨"
},
"date": "2016-03-03",
"tmp": {
"max": "15",
"min": "4"
},
"wind": {
"dir": "东北风",
"sc": "微风"
}
},
{
"astro": {
"sr": "06:42",
"ss": "18:09"
},
"cond": {
"code_d": "104",
"code_n": "101",
"txt_d": "阴",
"txt_n": "多云"
},
"date": "2016-03-04",
"tmp": {
"max": "19",
"min": "3"
},
"wind": {
"dir": "西南风",
"sc": "微风"
}
},
{
"astro": {
"sr": "06:40",
"ss": "18:10"
},
"cond": {
"code_d": "101",
"code_n": "101",
"txt_d": "多云",
"txt_n": "多云"
},
"date": "2016-03-05",
"tmp": {
"max": "11",
"min": "0"
},
"wind": {
"dir": "西北风",
"sc": "微风"
}
},
{
"astro": {
"sr": "06:39",
"ss": "18:11"
},
"cond": {
"code_d": "101",
"code_n": "101",
"txt_d": "多云",
"txt_n": "多云"
},
"date": "2016-03-06",
"tmp": {
"max": "9",
"min": "-2"
},
"wind": {
"dir": "东风",
"sc": "微风"
}
},
{
"astro": {
"sr": "06:37",
"ss": "18:12"
},
"cond": {
"code_d": "101",
"code_n": "101",
"txt_d": "多云",
"txt_n": "多云"
},
"date": "2016-03-07",
"tmp": {
"max": "8",
"min": "-1"
},
"wind": {
"dir": "北风",
"sc": "微风"
}
},
{
"astro": {
"sr": "06:36",
"ss": "18:13"
},
"cond": {
"code_d": "101",
"code_n": "101",
"txt_d": "多云",
"txt_n": "多云"
},
"date": "2016-03-08",
"tmp": {
"max": "8",
"min": "0"
},
"wind": {
"dir": "北风",
"sc": "微风"
}
}
],
"status": "ok"
}
]
}
Intboy 2016-03-02
  • 打赏
  • 举报
回复
public class HttpGetWeather
{
    private static final Log LOGGER = LogFactory.getLog(HttpGetWeather.class);

    public static void main(String[] args) throws Exception
    {
        String url = "http://apis.baidu.com/heweather/pro/attractions";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        NameValuePair params1 = new BasicNameValuePair("cityid", "CN10101010018A");
        params.add(params1);
        // for version 4.3+
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient httpClient = httpClientBuilder.build();

        // HttpClient httpClient = new DefaultHttpClient();
        // 连接时间
        // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
        // connectionTimeout);
        // 数据传输时间
        // httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
        // soTimeout);
        
        // Get请求
        HttpGet httpget = new HttpGet(url);
        try
        {
            // for version 4.3+ 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000)
                    .setConnectTimeout(2000).build();
            httpget.setConfig(requestConfig);

            // 设置参数
            String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Charset
                    .forName("UTF-8")));
            httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
            httpget.setHeader("apikey", "63768771fba86cb8f45097013d35074e");
            // 发送请求
            HttpResponse httpResponse = httpClient.execute(httpget);

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK)
            {
                LOGGER.error("Method failed:" + httpResponse.getStatusLine());
            }

            // 获取返回数据
            HttpEntity entity = httpResponse.getEntity();
            String body = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            if (entity != null)
            {
                EntityUtils.consume(entity);
            }
            System.out.println(body);
        } catch (ParseException e)
        {
            throw e;
        } catch (UnsupportedEncodingException e)
        {
            throw e;
        } catch (IOException e)
        {
            throw e;
        } catch (URISyntaxException e)
        {
            throw e;
        } finally
        {
            try
            {
                // for 4.3+
                httpClient.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            // httpget.releaseConnection();
            // httpClient.getConnectionManager().shutdown();
        }
    }
}
试试
------------------------课程介绍------------------------ 第1章 HTML、CSS、布局 第2章 JavaScript 介绍 第3章 作业讲解、编程的选择结构和函数返回值和库、css初步、函数参数 第4章 数组和字符串、作业讲解、debug大法 第5章 作业讲解、如何方便地用测试写代码、break&continue;语句、object、读文档、递归 第6章 网页中引入JavaScript代码、DOM、事件 第7章 数据类型、多行字符串和转义符号、高阶函数、匿名函数 第8章 事件委托、时间操作、标签的可编辑属性、(本地存储) 和 JSON 格式 第9章 作业选讲、抽象化, 如何封装功能, 如何组织代码结构、变量命名的方法 第10章 HTTP 协议 和 AJAX、DOM 事件机制, 事件冒泡和事件捕获 第11章 面向对象、ajax、作业和代码思路 第12章 找工作基础、ajax作业、api封装 第13章 jQuery 常见用法、课程重点、常用组件例如弹窗的制作 第14章 作业讲解 第15章 log的要素、git和github、js的一些高级内容 bind apply call、前端CSS框架Bootstrap和Pure 第16章 JS的历史现状和未来、什么是ES6有什么新东西、CSS最基础的套路 第17章 前端工程师 第1章 网址组成、端口、HTTP协议、web服务器 第2章 作业讲解、服务器框架、html和getpost传递参数 第3章 基本框架、框架解释、model解释 第4章 cookie讲解、session讲解、作业讲解和调试技巧 第5章 todo程序、todo的更新和删除、带用户功能的todo程序 第6章 jinja模板套路、类和其他、作业讲解 第7章 摘要算法、加盐保护密码-数据库索引原理、微博程序 第8章 传统数据库、sql注入和mongo安装使用、mongo日常使用 第9章 前端基础、dom和事件、js todo 第10章 ajax 第11章 css 第12章 linux基础 第13章 flask框架 第14章 使用sshkey连接linux服务器、rsa原理和git软件使用、使用git软件同步本地和服务器代码 第15章 flask的session和cookie、flask留言板&web;后端栈、flask博客套路 第16章 抓包&爬虫基础、爬虫精讲、编码&API; 第17章 数据结构基础和算法分析原理、链表队列栈和四大结构、平衡二叉搜索树和哈希表 第18章 bbs基础、bbs标题和回复、bbs其他 第19章 web安全和应对、服务器的配置文件处理、开发论坛的板块功能 第20章 论坛收尾、迁移mongo、性能 第21章 操作系统、python高级 第22章 python高级技巧、rpc实现和vagrant 第23章 架构、分布式、性能、聊天室项目 第24章 简历和工作、工作后的计划、学习的计划

67,516

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧