简体   繁体   English

Android:片段中的Http请求

[英]Android: Http request in fragment

I want to make a http request to get data from webpage. 我想发出http请求以从网页获取数据。 In the main status activity it works, but when i try it in a fragment it doesnt. 在主要状态活动中,它起作用,但是当我在一个片段中尝试它时,它不起作用。

MainStatusActivity.java: MainStatusActivity.java:

public class MainStatusActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
FragmentEngineer fengineer;
FragmentInternet finternet;
FragmentOverview foverview;
FragmentSettings fsettings;
FragmentStatus fstatus;
FragmentWlan fwlan;


public static String cookietoheader;
public String toStatusFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_status);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    fengineer = new FragmentEngineer();
    finternet = new FragmentInternet();
    foverview = new FragmentOverview();
    fsettings = new FragmentSettings();
    fstatus = new FragmentStatus();
    fwlan = new FragmentWlan();



    final String cookieFromLogin;
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if(extras == null) {
            cookieFromLogin= null;
        } else {
            cookieFromLogin= extras.getString("Cookie");
        }
    } else {
        cookieFromLogin= (String) savedInstanceState.getSerializable("Cookie");
    }


    cookietoheader = cookieFromLogin;

}
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_status, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.



    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        new PostClass2(this).execute();
        Intent intent = new Intent(getApplicationContext(), MainLoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    FragmentTransaction ftrans = getFragmentManager().beginTransaction();

    if (id == R.id.nav_status) {
        ftrans.replace(R.id.container, fstatus);
    } else if (id == R.id.nav_overview) {
        ftrans.replace(R.id.container, foverview);
    } else if (id == R.id.nav_internet) {
        ftrans.replace(R.id.container, finternet);
    } else if (id == R.id.nav_wlan) {
        ftrans.replace(R.id.container, fwlan);
    } else if (id == R.id.nav_settings){
        ftrans.replace(R.id.container, fsettings);
    } else if (id == R.id.nav_engineer){
        ftrans.replace(R.id.container, fengineer);
    }ftrans.commit();



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

FragmentInternet.class: FragmentInternet.class:

public class FragmentInternet extends android.app.Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;

private String cookies;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment FragmentInternet.
 */
// TODO: Rename and change types and number of parameters
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(this).execute();
}
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 {
            final TextView outputView = (TextView) findViewById(R.id.showOutput);
            URL url = new URL("http://speedport.ip/html/assistent/ea_internet_done.html");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Request URI", "/html/assistent/ea_internet_done.html");
            connection.setRequestProperty("Request Version", "HTTP/1.1");
            connection.setRequestProperty("Host", "speedport.ip");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp");
            connection.setRequestProperty("Upgrade-Insecure-Requests","1");

            //connection.setRequestProperty("Origin","http://speedport.ip");
            //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("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Referer","http://speedport.ip/html/login/index.html");
            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);

            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();
            String outtotext = responseOutput.toString();
            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

            FragmentInternet.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    outputView.setText(output);
                }
            });


        } 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() {
        //progress.dismiss();
    }

}*/


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_internet, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}
    /*
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}
    */
@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

} }

when i try it it shows underline : new PostClass(this).execute() (it says Postclass cannot be applied); 当我尝试它时,它显示以下划线:new PostClass(this).execute()(它说Postclass无法应用); and final TextView outputView = (TextView) findViewById(R.id.showOutput)(cannot resolve method); 最后的TextView outputView =(TextView)findViewById(R.id.showOutput)(无法解析方法);

The fragment works, the http request works if without the fragments(tried on blak activity) 片段有效,如果没有片段,则http请求有效(尝试空白活动)

Replace your onCreate() by this : 将您的onCreate()替换为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM