Java代码在IDE上工作但在android studio中不起作用

时间:2015-08-13 14:24:54

标签: java android android-studio intellij-idea

我编写了一个简单的代码来从服务器获取响应。它在IntelliJ Idea IDE上工作正常,并返回预期的结果。代码:

# vtk DataFile Version 3.0
vtk output
ASCII
DATASET STRUCTURED_GRID
DIMENSIONS 2 3 1
POINTS 6 float
0 0 0
1 0 0
0 1 0
1 1 0
0 2 1
1 2 1
CELL_DATA 2
SCALARS cellData float 1
LOOKUP_TABLE default
0.123 0.456

然而,当我将此代码复制并粘贴到android studio时,此代码停止工作。在我看来,try块永远不会执行,因为当我将它分配给textView时,statusCode输出显示50。这是android studio代码:

import sun.org.mozilla.javascript.internal.json.JsonParser;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainCode {

    public static void main(String... args){
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        Integer result = 0;
        Integer statusCode = 50;
        String response="";
        try{
            URL url = new URL("http://127.0.0.1/Customers/getAllCustomers.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            statusCode = urlConnection.getResponseCode();
            if (statusCode ==  200) {
                    inputStream = new BufferedInputStream(urlConnection.getInputStream());
                    response = convertInputStreamToString(inputStream);
//                    parseResult(response);
                result = 1; // Successful
            }else{
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e){
        }
        System.out.print(response);
    }
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null){
            result += line;
        }

            /* Close Stream */
        if(null!=inputStream){
            inputStream.close();
        }
        return result;
    }

}

更新的代码:使用AsyncTask

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends Activity {

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

    private static String callThis(){
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        Integer result = 0;
        Integer statusCode = 50;
        String response="";
        try{
            URL url = new URL("http://127.0.0.1/Customers/getAllCustomers.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            statusCode = urlConnection.getResponseCode();
            if (statusCode ==  200) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                response = convertInputStreamToString(inputStream);
//                    parseResult(response);
                result = 1; // Successful
            }else{
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e){
        }
        return statusCode+response;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null){
            result += line;
        }

            /* Close Stream */
        if(null!=inputStream){
            inputStream.close();
        }
        return result;
    }

}

logcat的:

public class MainActivity extends Activity {

    private static final String TAG = "Http Connection";
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.textView);
        new AsyncHttpTask().execute();
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            InputStream inputStream = null;
            HttpURLConnection urlConnection = null;
            Integer result = 0;
            String response="";
            int statusCode = 10;
            try {
                /* forming th java.net.URL object */
                URL url = new URL("http://127.0.0.1/Customers/getAllCustomers.php");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                if (statusCode ==  200) {
                    inputStream = new BufferedInputStream(urlConnection.getInputStream());
                    response = convertInputStreamToString(inputStream);
                    result = 1; // Successful
                }else{
                    result = 0; //"Failed to fetch data!";
                }

            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return response + statusCode; //"Failed to fetch data!";
        }
        @Override
        protected void onPostExecute(String result) {
            /* Download complete. Update UI */
            textView.setText(result);
        }
    }


    private String convertInputStreamToString(InputStream inputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));

        String line = "";
        String result = "";

        while((line = bufferedReader.readLine()) != null){
            result += line;
        }

            /* Close Stream */
        if(null!=inputStream){
            inputStream.close();
        }

        return result;
    }

}

1 个答案:

答案 0 :(得分:0)

当我使用127.0.0.1访问我的服务器时,我无法访问它,因为那也是分配给我的android模拟器的ip。所以代码适用于java IDE,但不适用于模拟器。我不得不用10.0.2.2替换它以使其工作。