Android App - onCreateView中的HttpURLConnection

时间:2017-07-24 22:30:47

标签: java android

我刚开始学习开发Android应用程序,我需要调用一个URL来获取JSON响应。

这是我的java类: -

public class SpeakersFragment extends Fragment {

    List<String> titles;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {



        View view = inflater.inflate(R.layout.fragment_speakers, container, false);

        initData();
        RecyclerView rv = (RecyclerView)view.findViewById(R.id.info_speaker_recycler);
        rv.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);
        RecyclerAdapter adapter = new RecyclerAdapter(getActivity(), titles);
        rv.setAdapter(adapter);

        new GetSpeakersList().execute(URL);

        return view;
    }


public class GetSpeakersList extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {

            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                    Log.v("CatalogClient", server_response);
                }

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

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            Log.e("Response", "" + server_response);


        }
    }

    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

当我检查日志时,响应根本不存在。我尝试创建一个新项目,如果我在onCreate()而不是onCreateView中调用GetSpeakersList,它可以正常工作。

可以指导我如何让它发挥作用吗?谢谢!

2 个答案:

答案 0 :(得分:1)

使用AsyncTask对于持续的网络请求来说非常麻烦:尝试使用流行的,支持良好的库进行网络化:以下是两个流行的:

1)Retrofit

OR

2)Volley

答案 1 :(得分:0)

这就是我要求数据的方式,希望你可以将它用于你的手段

urlConnection = new URL("www.example.com");
connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type","application/json;charset=UTF-8");
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
connection.connect();

dataOutputStream = new 
DataOutputStream(connection.getOutputStream());
Log.d("OUTPUT :",param);
dataOutputStream.writeBytes(param);
dataOutputStream.flush();
dataOutputStream.close();

//传入数据

InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new 
InputStreamReader(in));
result = new StringBuilder(16384);
String line;
while ((line = reader.readLine()) != null)
{
  result.append(line);
}
Log.d("INPUT :",result.toString());