Android HTTP request wierd 404 not found issue

送分小仙女□ 提交于 2019-12-24 07:12:57

问题


In my application, I am trying to hit a URL which I do using the following code

  try {
    url = new URL(serverURL);

    httpURLConnection = (HttpURLConnection) url.openConnection();

    int timeout = 30000;
    httpURLConnection.setConnectTimeout(timeout);
    httpURLConnection.setReadTimeout(timeout);

    httpURLConnection.connect();

    String httpResponseMessage = httpURLConnection.getResponseMessage();
    responseCode = httpURLConnection.getResponseCode();

    Log.i(LOG_TAG,"Response code "+responseCode);

    } catch (Exception e) {
    e.printStackTrace();
    }

The (confidential) URL when opened through browser (on computer as well as on phone), works perfectly and the response is as expected. But when I hit the same URL via the above piece of code, it gives me response code 404 (NOT FOUND). Can anybody tell me what the issue can be? (Sorry, can not post the URL since is highly confidential.)


回答1:


Are you sure that you have the android.permission.INTERNET declared in your AndroidManifext.xml?




回答2:


Problem solved :)

      try {

            url = new URL(serverURL);

            Log.i(LOG_TAG, url+"");
            HttpGet method= new HttpGet(new URI(serverURL));
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(serverURL));
            HttpResponse response = client.execute(method);
            responseCode = response.getStatusLine().getStatusCode();

            Log.i(LOG_TAG,"Response code response "+response);
            Log.i(LOG_TAG,"Response responseCode "+responseCode);
        } catch (Exception e) {
            e.printStackTrace();
        }



回答3:


Actually you don't even need following two lines in your code.

HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));

One HttpGet is enough and you don't need it twice.




回答4:


Not sure if this matters but I had the exact problem.

I was doing some explicity port 80 stuff and removing this line made it work:

HttpHost host = new HttpHost(targetHost, 80, "http");


来源:https://stackoverflow.com/questions/10835845/android-http-request-wierd-404-not-found-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!