Java Android应用程序-onCreateView中的HttpURLConnection

Java Android应用程序-onCreateView中的HttpURLConnection,java,android,Java,Android,我刚刚开始学习开发android应用程序,我需要调用一个URL来获得JSON响应 这是我的java类:- public class SpeakersFragment extends Fragment { List<String> titles; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,

我刚刚开始学习开发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();
    }
公共类SpeakersFragment扩展片段{
列出标题;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图=充气机。充气(R.layout.fragment_扬声器,容器,错误);
initData();
RecyclerView rv=(RecyclerView)view.findViewById(R.id.info\u speaker\u recycler);
rv.setHasFixedSize(真);
LinearLayoutManager llm=新的LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
RecyclerAdapter=新的RecyclerAdapter(getActivity(),titles);
rv.设置适配器(适配器);
新建getSpeakerList().execute(URL);
返回视图;
}
公共类GetSpeakerList扩展了AsyncTask{
字符串服务器响应;
@凌驾
受保护的字符串背景(字符串…字符串){
网址;
HttpURLConnection-urlConnection=null;
试一试{
url=新url(字符串[0]);
urlConnection=(HttpURLConnection)url.openConnection();
int responseCode=urlConnection.getResponseCode();
if(responseCode==HttpURLConnection.HTTP\u确定){
server_response=readStream(urlConnection.getInputStream());
Log.v(“CatalogClient”,服务器响应);
}
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
Log.e(“响应”,“服务器+响应”);
}
}
私有字符串读取流(输入流输入){
BufferedReader reader=null;
StringBuffer响应=新的StringBuffer();
试一试{
reader=新的BufferedReader(新的InputStreamReader(in));
字符串行=”;
而((line=reader.readLine())!=null){
响应。追加(行);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(读卡器!=null){
试一试{
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
返回response.toString();
}
当我检查日志时,响应根本不存在。我尝试创建一个新项目,如果我在onCreate()而不是onCreateView中调用GetSpeakerList,效果会很好


您能指导我如何实现这一点吗?谢谢!

对于持续的网络请求,使用异步任务可能会非常麻烦:尝试使用一个流行的、受良好支持的库进行网络连接:以下是两个流行的库:

(一)


2)

我就是这样要求数据的,希望你能利用它来达到你的目的

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());

虽然建议使用新的库是好的,但我认为这个答案实际上并没有回答这个问题。这个问题说“我需要调用一个URL来获得JSON响应”。OP没有说他们特别想使用HttpURLConnection,但可能认为他们必须这样做,因为他们刚刚开始学习Android开发。这会告诉他们实现主要目标的其他方法。尝试在片段的onActivityCreated()或onCreate()中启动asynctask