从站点

时间:2015-12-28 14:23:40

标签: android json okhttp

所以我使用okHttp客户端从网站获取一些天气数据。直到现在我编写代码只是为了获取json数据并显示它,但我没有得到数据。通过我检查网址两次的方式,它的工作原理。下面是代码:

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        OkHttpClient client = new OkHttpClient();
        final TextView tv = (TextView)rootView.findViewById(R.id.display_json_data);
        Request request = new Request.Builder().url("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&APPID=c82bfbedf3241dd88e356bffea122761").build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String jsonData = response.body().string();
                tv.setText(jsonData);
            }
        });

        return rootView;

    }
}

我已添加清单中所需的权限。我在设备上运行时没有输出。请帮忙。

2 个答案:

答案 0 :(得分:1)

检查 AndroidManifest中的 权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

您可以使用UI线程 “runOnUiThread”:

OkHttpClient client = new OkHttpClient();
final TextView tv = (TextView) findViewById(R.id.display_json_data);
Request request = new Request.Builder().url("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&APPID=c82bfbedf3241dd88e356bffea122761").build();
Call call = client.newCall(request);
call.enqueue(new Callback() {

     @Override
     public void onFailure(Request request, IOException e) {

     }

     @Override
     public void onResponse(Response response) throws IOException {
        final String jsonData = response.body().string();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
               tv.setText(jsonData);
            }
        });
     }
});

答案 1 :(得分:0)

你可以试试这个。

  Response response = client.newCall(request).execute();
  return response.body().string();

Permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

参考链接http://square.github.io/okhttp/