Binh Tran Van
Binh Tran Van

Reputation: 39

Why does HttpURLConnection fail on android but succeed in java Eclipse?

I don't know why HttpURLConnection fails on android but succeeds in java Eclipse. I have been facing that problem for many days and trying to solve it but have never pass it. The code in my case as followings:

try {  
        url = "https://mobitrade.vpbs.com.vn:8080/getlistckindex/hnx";
        URL urlGetSymbol = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlGetSymbol.openConnection();
        con.setRequestMethod("GET");
        con.setReadTimeout(15000);
        con.setConnectTimeout(15000);
        con.setDoOutput(true);
        con.connect();
        int responseCode = con.getResponseCode();
        BufferedReader in =new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String responseString = response.toString().replaceAll("\\[", "").replaceAll("\\]", "")
                .replaceAll("\"", "");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

The code works fine in java eclipse but don't work on android due to con.connect() gets error.

Upvotes: 0

Views: 146

Answers (2)

hyojoon
hyojoon

Reputation: 613

Add

<uses-permission android:name="android.permission.INTERNET"/> 

to your Androidmanifest.xml

Upvotes: 0

Bheem  Singh
Bheem Singh

Reputation: 707

I think you are using different api packages for HttpURLConnection so please check that. you can use java.net.HttpURLConnection api for the same.

Upvotes: 1

Related Questions