简体   繁体   English

Android-连接到本地主机时HTTP无法正常工作

[英]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. 我使用三星Galaxy S4来测试代码。

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 看看apache http客户端NafHttpAuthStrategyDefault

BTW I'd recommend using AsyncTask for your background task. 顺便说一句,我建议您将AsyncTask用于后台任务。 And to avoid cumbersome and error prone coding with HttpURLConnection , you could use an abstraction library. 为了避免使用HttpURLConnection繁琐且容易出错的编码,可以使用抽象库。 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'. 因为您的网络服务器的内容协商应该返回'application / json'。

I found a work around this using HttpURLConnection method. 我发现使用HttpURLConnection方法解决此问题。 It worked perfectly. 效果很好。 For more details, see this HttpURLConnection 有关更多详细信息,请参见此HttpURLConnection。

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

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