简体   繁体   中英

Android - HTTP not working when connecting to localhost

I am trying to read a webpage on the localhost using this code. It works when trying to read actual webpages but it gives this message on trying on my localhost webpage. Can someone suggest the error or give an alternate solution? Thanks.

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button sendbutton = (Button)findViewById(R.id.button1);
        sendbutton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Log.i("clicked","button");
            Thread th = new Thread()
            {
                public void run()
                {
                    try
                    {
                    Log.i("clicked", "Button");
                    String url = "http://140.254.191.124/test/index.php";
                    Log.i("inside","thread");
                    String tmp = ReadWebPage(url);
                    Log.i("response", tmp);
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            };
            th.start();
        }});

        }

    public String ReadWebPage (String URL){
        BufferedReader in = null;
        String page = "null";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        try{
            request.setURI(new URI(URL));
            request.addHeader("accept", "application/json");
            HttpResponse response = null;
            response = client.execute(request);
            in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }

            page = sb.toString();
            System.out.println(page);
            Toast.makeText(MainActivity.this, page, Toast.LENGTH_LONG).show();
            if (in != null) in.close();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return page;
    }

This is the message i get. I use a Samsung Galaxy S4 to test the code.

01-31 19:28:20.027: I/clicked(9133): button
01-31 19:28:20.027: I/clicked(9133): Button
01-31 19:28:20.027: I/inside(9133): thread
01-31 19:28:20.027: I/APACHE HTTP (thCr=180433) - NafHttpAuthStrategyDefault(9133): (thUse=180433) NafHttpAuthStrategyDefault()
01-31 19:28:20.027: I/APACHE HTTP (thCr=180433) - KeeperManager(9133): (thUse=180433) INITIALIZATION of shared resources
01-31 19:28:20.027: I/APACHE HTTP (thCr=180433) - AndroidContextProviderImpl(9133): (thUse=180433)    currentActivityThread=android.app.ActivityThread@43099610
01-31 19:28:20.057: I/APACHE HTTP (thCr=180433) - NafHttpAuthStrategyDefault(9133): (thUse=180433)    cached value : gbaSupportIsPossible=null
01-31 19:28:20.057: I/APACHE HTTP (thCr=180433) - NafHttpAuthStrategyDefault(9133): (thUse=180433)    The current context is NOT a context of GBA service.
01-31 19:28:20.067: I/APACHE HTTP (thCr=180433) - GbaSupportPermissionRequestCheckerImpl(9133): (thUse=180433) isCurrentProcessRequestedGba()#finished   result=false
01-31 19:28:20.067: I/APACHE HTTP (thCr=180433) - GbaSupportPermissionRequestCheckerImpl(9133): (thUse=180433) isCurrentProcessAllowedToUseGba()#started   result=false
01-31 19:28:20.067: I/APACHE HTTP (thCr=180433) - NafHttpAuthStrategyDefault(9133): (thUse=180433)    The GBA permission wasn't requested for this process.
01-31 19:28:20.067: I/APACHE HTTP (thCr=180433) - NafHttpAuthStrategyDefault(9133): (thUse=180433) It is impossible to support GBA now (many possible reasons: no Android Context, current client is GBA service, etc.), then it will be just usual HTTP.
01-31 19:28:20.067: I/APACHE HTTP (thCr=180433) - NafRequestExecutorWrapperRedirectionHandler(9133): (thUse=180433)    It isn't GBA flow, redirection responses are not handled.

Have a look at apache http client NafHttpAuthStrategyDefault

BTW I'd recommend using AsyncTask for your background task. And to avoid cumbersome and error prone coding with HttpURLConnection , you could use an abstraction library. Here is an option and a list of alternatives .

Another point: Are you sure you want to load a web-page? Because content-negotiation of your web-server should return 'application/json'.

I found a work around this using HttpURLConnection method. It worked perfectly. For more details, see this HttpURLConnection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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