【问题标题】:HttpURLConnection doesn't workHttpURLConnection 不起作用
【发布时间】:2017-07-13 05:40:38
【问题描述】:

我正在尝试在我的 android projet 中使用 web 服务数据

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

【问题讨论】:

  • 使用扩展异步任务的类
  • 检查您的设备中是否有互联网。
  • 我在使用 AsycTask 时遇到了同样的问题
  • 是的,我的设备上有互联网
  • 我复制您的代码并运行它...有效。你的设备操作系统版本是多少?

标签: android android-studio httpurlconnection


【解决方案1】:

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

【讨论】:

  • 我已将 放入我的清单中。我已经删除了 if 语句(响应 == 200)。还是不行。
【解决方案2】:
 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();

// 如果你想使用编码器下面的一些值发送一些数据,否则不需要 数据 = URLEncoder.encode("one", "UTF-8") + "=" + URLEncoder.encode(a, "UTF-8"); 数据 += "&" + URLEncoder.encode("two", "UTF-8") + "=" + URLEncoder.encode(b, "UTF-8"); 数据 += "&" + URLEncoder.encode("三", "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();
        }
    }

【讨论】:

  • 你是用PHP脚本链接的吗??
【解决方案3】:

你得到类似线程 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多