0

我现在真的很痛苦,请帮我解决这个问题。我以前也尝试过向我的本地主机发出 http 请求,一切正常,但现在它不起作用,我不知道为什么。

我正在尝试从以下代码发出请求。

    HttpClient httpclient = new DefaultHttpClient();
    String result="";
    try
     {
        HttpPost httppost = new HttpPost("http://[ip]/php/untitled.php");


        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("email",this.userEmail));
        nameValuePairs.add(new BasicNameValuePair("pwd",this.userpassword));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity=response.getEntity();
        if(entity!=null)
        {
              InputStream inputStream=entity.getContent();
              result= convertStreamToString(inputStream);
        }
    }
    catch (ClientProtocolException e) 
    {
        Log.e("errorhai",e.getMessage());
    }
    catch (IOException e) 
    {
        Log.e("errorhai",e.getMessage());
    }
        return result;

我还添加了互联网权限,但它仍然一直说

Connect to [ip] timed out.

当我在浏览器中输入网址时,它工作正常,但在这里不起作用。请告诉我这个问题的原因是什么?

4

2 回答 2

0

您的问题可能与登录有关。您的脚本是否需要先发制人的身份验证?您是否有登录失败的错误页面?

为了请求具有抢先式 http 基本身份验证的页面,我正在使用以下有效代码。试试看,如果它也适合你。

    DefaultHttpClient httpclient         = null;
    HttpParams        params             = new BasicHttpParams();
    HttpResponse      response           = null;
    HttpEntity        entity             = null;
    // Set connection parameter
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    httpclient = new DefaultHttpClient(params);
    // Create a post statement
    HttpPost httppost = new HttpPost(Constants.urlLogin);
    httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY,   CookiePolicy.RFC_2965);
    httppost.getParams().setParameter("http.protocol.single-cookie-header", true);
    httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("login_name", this.username));
    nvps.add(new BasicNameValuePair("login_passwd", this.userpassword));
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    response = httpclient.execute(httppost);
    entity = response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();
    String loadedContent = null;
    if (entity != null)
    {
        loadedContent = EntityUtils.toString(entity, HTTP.UTF_8);
        // loadedContent =
        // Helper.convertStreamToString(entity.getContent());
        entity.consumeContent();
    }
    if (statusCode != (HttpStatus.SC_OK))
    {
        throw new ServerCommunicationErrorException();
    } else if (!loadedContent.contains("Logout"))
    {
        // Login failed
        throw new LoginFailedException();
    }

如您所见,如果登录无法确定登录过程,我会得到一个“未登录”页面。此外,我设置了一些参数,这对您来说可能也很有趣。您可以在此处查看有关参数的更多信息。

于 2013-01-31T15:05:01.300 回答
0

您可以设置超时参数来处理此类异常:

HttpParams httpParameters = new BasicHttpParams();

        /* Set the timeout in milliseconds until a connection is established.
            The default value is zero, that means the timeout is not used.*/  

        int timeoutConnection = 60*1000*1;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        /* Set the default socket timeout (SO_TIMEOUT) 
            in milliseconds which is the timeout for waiting for data.  */
        int timeoutSocket = 60*1000*1;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpClient client = new DefaultHttpClient(httpParameters);

        //HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse;
        try {
            /** Finally, we send our request using HTTP. This is the synchronous
                long operation that we need to run on this thread. */
            httpResponse = client.execute(request);

            /*int responseCode = httpResponse.getStatusLine().getStatusCode();
            String message = httpResponse.getStatusLine().getReasonPhrase();*/

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                String res = convertStreamToString(instream);
                MLog.v("HTTP RESPONSE : ", "Res :-"+res);

                if(!res.trim().equalsIgnoreCase("[]")){
                    response.setResult(res);
                    response.setSuccess(true);
                }else{
                    response.setSuccess(false);
                    response.setErrorMessage(AppConstant.RECORD_NOT_FOUND);
                }
                /** Closing the input stream will trigger connection release */
                instream.close();
            }else{
                response.setSuccess(false);
                response.setErrorMessage(AppConstant.NETWORK_ERROR);
            }
        }   
        catch (Exception e) {
            //client.getConnectionManager().shutdown();
            e.printStackTrace();

            response.setSuccess(false);
            response.setErrorMessage(AppConstant.NETWORK_ERROR);
        }

        //you can again try to send request , if your response is not sucess.
        //retryHttpRequestIfNotSucess();
于 2013-02-08T07:23:39.960 回答