简体   繁体   English

我的Android应用无法连接到服务器

[英]My Android app can't connect to server

I'm tying to read data from server I'm using xampp) but the data is empty this is my connect activity: 我想从使用xampp的服务器读取数据),但是数据为空,这是我的连接活动:

public String link="";
public AsyncTaskConnect(String link){
    this.link=link;
}
@Override
protected Object doInBackground(Object[] params) {
    try{
        URL url=new URL(link);
        URLConnection connection=url.openConnection();
        BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder builder=new StringBuilder();
        String line=null;
        while((line=reader.readLine())!=null){
            builder.append(line);
        }
        MainActivity.data=builder.toString();
    }catch (Exception e){
    }
    return "";
}

this is main activity: 这是主要活动:

public static String data="";
TextView txthello;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txthello=(TextView)findViewById(R.id.txthello);
    new AsyncTaskConnect("http://192.168.1.2/digikala/test.php").execute();
    txthello.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,data,Toast.LENGTH_LONG).show();
        }
    });
}

but it doesn't work, what should I do? 但它不起作用,我该怎么办?

Using HttpURLConnection , it extends your URLConnection so I am changing just a little to your code. 使用HttpURLConnection ,它扩展了您的URLConnection因此我对您的代码进行了一些更改。 Given you have your query in the String variable link , this should work just as fine. 给定您在String变量link中的查询,它应该可以正常工作。

try {
                URL url = new URL(link);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();

                int responseCode = connection.getResponseCode();
                Log.i(TAG, "POST Response Code: " + responseCode);

                //Takes data only if response from WebService is OK
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    //Stores input line by line in response
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
} catch (Exception e) {
            e.printStackTrace();
}

if you follow this snippet, response is the string which contains all of the response you get from your webservice, you can further convert it to JSON if you want. 如果遵循此代码段,则response是包含从Web服务获得的所有响应的字符串,如果需要,可以将其进一步转换为JSON。

Hope it works! 希望它能起作用!

but the data is empty 但数据为空

Because execute is not a blocking call. 因为execute不是阻塞调用。

Assuming you can actually reach the server, MainActivity.data is an empty String until after the Asynctask onPostExecute 假设您实际上可以到达服务器,则MainActivity.data是一个空字符串,直到Asynctask onPostExecute之后

You can either use Volley, Okhttp, Retrofit, etc to simplify your networking code 您可以使用Volley,Okhttp,Retrofit等来简化网络代码

Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley Android网络库的比较:OkHTTP,Retrofit和Volley

or add callbacks into your Asynctask 或在Asynctask中添加回调

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? 由于AsyncTask是一个单独的类,如何使OnPostExecute()的结果进入主要活动?

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

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