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

时间:2017-08-27 14:02:37

标签: java android read-data

我想使用xampp从服务器I读取数据但是数据是空的 这是我的连接活动:

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 "";
}

这是主要活动:

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

但它不起作用,我该怎么办?

2 个答案:

答案 0 :(得分:0)

使用HttpURLConnection,它会扩展您的URLConnection,因此我只更改了您的代码。鉴于您在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();
}

如果您遵循此片段,则response是包含您从Web服务获得的所有响应的字符串,如果需要,您可以进一步将其转换为JSON。

希望它有效!

答案 1 :(得分:0)

  

但数据为空

因为execute不是阻塞调用。

假设您实际可以访问服务器,{Asperctask onPostExecute

之前MainActivity.data是一个空字符串

您可以使用Volley,Okhttp,Retrofit等来简化您的网络代码

Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley

或将回调添加到Asynctask

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?