中国和世界天气全能版 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);
}
});
}
}
...全文
204 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用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();
        }
    }
}
试试

67,550

社区成员

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

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