HttpURLConnection不起作用

时间:2017-07-13 05:40:39

标签: android android-studio httpurlconnection

我正在尝试在我的android projet中使用webservice数据

        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL("http://ip.jsontest.com/");
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            int response = conn.getResponseCode(); //fail
            Log.d("","success!");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            conn.disconnect();
        }

调用conn.getResponseCode()时代码失败。 调用conn.getInputStream()conn.getContent()时也是如此。

不会抛出异常。 conn.disconnect()(在finally块中)在conn.connect()

之后执行

在我的AndroidManifest中我有

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

修改

使用AsyncTask

时遇到同样的问题
public class DataAccess extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //snackbar.show();
    }

    @Override
    protected String doInBackground(String... strings) {
        InputStream inputStream = null;
        HttpURLConnection conn = null;

        String stringUrl = strings[0];
        try {
            URL url = new URL(stringUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            int response = conn.getResponseCode();

            inputStream = conn.getInputStream();
            if (inputStream == null) {
                return null;
            }

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader reader = new BufferedReader(inputStreamReader);
            StringBuffer buffer = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
                buffer.append("\n");
            }

            return new String(buffer);
        } catch (IOException e) {
            return null;
        }
        finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException ignored) {
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (s == null) {
            //resultsTextView.setText("Erreur");
        } else {
            //resultsTextView.setText(s);
        }
        //snackbar.dismiss();
    }
}

3 个答案:

答案 0 :(得分:0)

 public class example extends AsyncTask<String,String,String>
    {

        @Override
        protected String doInBackground(String... params) {
            String link="give the link here";
            String data= null;
            try {
                URL url=new URL(link);
                URLConnection conn=url.openConnection();

//如果您想使用某些值发送一些数据,请使用编码器以下的其他值                     data = URLEncoder.encode(“one”,“UTF-8”)+“=”+ URLEncoder.encode(a,“UTF-8”);                     数据+ =“&amp;” + URLEncoder.encode(“two”,“UTF-8”)+“=”+ URLEncoder.encode(b,“UTF-8”);                     数据+ =“&amp;” + URLEncoder.encode(“three”,“UTF-8”)+“=”+ URLEncoder.encode(c,“UTF-8”);

                conn.setDoOutput(true);
                OutputStreamWriter osw=new OutputStreamWriter(conn.getOutputStream());
                osw.write(data);
                osw.flush();
                osw.close();
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line,sb="";
                while((line=br.readLine())!=null)
                {
                    sb+=line;
                }
                return sb;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return  new String(e.getMessage().toString());
            }

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            // It will get the response from server
            Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
        }
    }

答案 1 :(得分:0)

响应代码200用于成功的HTTP请求。 因此,请将if (response != 200)替换为if (response == 200)。 使用<uses-permission android:name="android.permission.INTERNET" />更改您的权限。

答案 2 :(得分:0)

你得到的东西像线程StrictMode ??? 尝试在执行异步任务之前调用此方法。

https://developer.android.com/reference/android/os/StrictMode.ThreadPolicy.Builder.html

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
     .detectAll()
     .penaltyLog()
     .build();  StrictMode.setThreadPolicy(policy);