Alex Iachimov
Alex Iachimov

Reputation: 31

HTTP Client on Android

I have some problem with my HTTP Client project, with HTTP Method GET, The problem is, when i run my app on Android Emulator it works perfect, when i use my code in Java Desktop app, it works too, but when i import in APK file and load on my Android device, i does not works at all, I don't know why.

Class with Get Method:

public class httpGetExClass {
    public String getInternetData() throws Exception {

        BufferedReader in = null;
        String data = null;
        try {
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://yumecms.com/absolvent/public/");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in .readLine()) != null) {
                sb.append(l + nl);
            } in .close();
            data = sb.toString();
            return data;
        } finally {
            if ( in != null) {
                try { in .close();
                    return data;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

This is the MainActivity

public class MainActivity extends Activity implements OnClickListener {

    TextView tv1;@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.textView1);
    }

    @Override
    public void onClick(View arg0) {
        httpGetExClass httpGet = new httpGetExClass();
        httpPostExClass httPost = new httpPostExClass();
        switch (arg0.getId()) {
            case R.id.buttonEnter:

                try {
                    Toast.makeText(this, "!!!!", Toast.LENGTH_SHORT).show();
                    String returned = httpGet.getInternetData();
                    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
                    tv1.setText(returned);
                } catch (Exception e) {
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }


                break;
        }

    }
}

Upvotes: 0

Views: 106

Answers (1)

zdebra
zdebra

Reputation: 998

Your code is blocking and it's not allowed in Android. You must use another thread for your httpclient or use android specific AsyncTask.

Upvotes: 1

Related Questions