HttpURLConnection得到403错误(localhost)? - Android

时间:2016-03-06 07:18:13

标签: android android-asynctask

我正在使用HttpURLConnection来连接到localhost,我将我的手机与USB tethering连接到我的PC(windows 10),然后我测试我的应用不要让我得到结果,得到我403。我的结果结构是JSON:

{"0":2,"1":3,"2":4,"HELLO":2,"OK":"LOLO"}

贝娄是我的代码:

public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CatalogClient client = new CatalogClient();
        client.execute("http://192.168.42.104/web/MySite/index.php");
      }
}

我的AsyncTask代码是:

public class CatalogClient extends AsyncTask<String, String, JSONArray> {
    String responseString;
    @Override
    protected JSONArray doInBackground(String... params) {
        URL url;
        HttpURLConnection urlConnection = null;
        JSONArray response = new JSONArray();

        try {
            url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);
            urlConnection.connect();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                responseString = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", responseString);
                response = new JSONArray(responseString);
            } else {
                Log.v("CatalogClient", "Response code:" + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
        }
        return response;
    }


    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                Log.i("LOG",line);
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "NULL";
    }
}

我从cmd获得IP:

enter image description here

注意:我使用的是UwAmpApache port is 80

0 个答案:

没有答案