Android Http响应仅在第二次单击后显示

时间:2016-03-13 11:38:59

标签: android android-fragments get httprequest

当我点击导航抽屉菜单时,我正在尝试制作 HTTP GET ,它会调用一个片段,我的HTTP代码就在该片段中。当我先点击它时它不会显示响应数据(但是在logcat中我可以看到HTTP get是发送和接收的)但当我点击导航抽屉中的另一个菜单时,再次尝试原始(它会生成另一个HTTP)请求)它显示我想要的。可能是什么问题?

public class FragmentInternet extends android.app.Fragment {

private static final String ARG_PARAM1 = "param1";

private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;

private String cookies;
private String textout;
private TextView t;

public FragmentInternet() {
    // Required empty public constructor
}

public static FragmentInternet newInstance(String param1, String param2) {
    FragmentInternet fragment = new FragmentInternet();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    new PostClass(getContext()).execute();
    cookies = MainStatusActivity.cookietoheader;

}

class PostClass extends AsyncTask<String, Void, Void> {

    private final Context context;


    public PostClass(Context c){

        this.context = c;
    }


    @Override
    protected Void doInBackground(String... params) {
        try {
            URL url = new URL("http://example.json");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Request URI", "/example.json");
            connection.setRequestProperty("Request Version", "HTTP/1.1");
            connection.setRequestProperty("Host", "example.com");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept","application/json, text/javascript, */*");
            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
            connection.setRequestProperty("Referer","http://speedport.ip/html/content/internet/connection.html?lang=en");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "hu-HU,hu;q=0.8,en-US;q=0.6,en;q=0.4");
            connection.setRequestProperty("Cookie", cookies);

            String responseMessage = connection.getResponseMessage();
            int responseCode = connection.getResponseCode();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
            output.append(System.getProperty("line.separator")  + "Response message " + responseMessage);
            output.append(System.getProperty("line.separator") + "Type " + "GET");
            output.append(System.getProperty("line.separator") + "Cookie " + cookies);
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while((line = br.readLine()) != null ) {
                responseOutput.append(line);
            }
            br.close();

            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
            textout = responseOutput.toString();

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

    protected void onPostExecute() {
        t.setText(textout);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.fragment_internet, container,false);
    t = (TextView) myInflatedView.findViewById(R.id.showOutput);
    t.setText(textout);
    return myInflatedView;
}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

编辑:工作代码感谢carthurs:

public class FragmentInternet extends android.app.Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private String cookies;
private String textout;
private TextView t;

public FragmentInternet() {
    // Required empty public constructor
}
public static FragmentInternet newInstance(String param1, String param2) {
    FragmentInternet fragment = new FragmentInternet();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    cookies = MainStatusActivity.cookietoheader;
}
class PostClass extends AsyncTask<String, Void, Void> {
    private final Context context;
    public PostClass(Context c){
        this.context = c;
    }
    @Override
    protected Void doInBackground(String... params) {
        try {
            URL url = new URL("http://examlpe.json");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Request URI", "/example.json");
            connection.setRequestProperty("Request Version", "HTTP/1.1");
            connection.setRequestProperty("Host", "example.com");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept","application/json, text/javascript, */*");
            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
            connection.setRequestProperty("Referer","http://speedport.ip/html/content/internet/connection.html?lang=en");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "hu-HU,hu;q=0.8,en-US;q=0.6,en;q=0.4");
            connection.setRequestProperty("Cookie", cookies);

            String responseMessage = connection.getResponseMessage();
            int responseCode = connection.getResponseCode();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
            output.append(System.getProperty("line.separator")  + "Response message " + responseMessage);
            output.append(System.getProperty("line.separator") + "Type " + "GET");
            output.append(System.getProperty("line.separator") + "Cookie " + cookies);
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while((line = br.readLine()) != null ) {
                responseOutput.append(line);
            }
            br.close();

            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
            textout = output.toString();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(Void ignored) {
        t.setText(textout);
    }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.fragment_internet, container,false);
    t = (TextView) myInflatedView.findViewById(R.id.showOutput);
    t.setText(textout);
    new PostClass(getContext()).execute();
    return myInflatedView;
}
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}
@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {
    void onFragmentInteraction(Uri uri);
}

}

1 个答案:

答案 0 :(得分:0)

您的onPostExecute()未被正确调用,因为其签名与您AsyncTask期望的内容不符。

当您创建AsyncTask<X,Y,Z>时,您声明类型Z将是protected Z doInBackground()的返回类型,并且它将是onPostExecute(Z myZ)的参数。这样做的目的是允许将背景计算的结果传递给onPostExecute

在您的情况下,您已声明结果为Void,因此您需要更改 onPostExecute()onPostExecute(Void ignored) 以便签名匹配,允许它被正确调用。