草庐IT

android - 执行 http POST 返回 HTML 而不是 JSON

coder 2023-11-25 原文

编辑 完全重新处理问题以便更好地理解

我必须使用 2 个 POST 参数查询给定的 url http://api.bf3stats.com/pc/player/:'player'(用于播放器名称)和'opt'(用于选项)。我已经在 http://www.requestmaker.com/ 上测试过了具有以下数据:player=Zer0conf&opt=all。我得到了正确的 JSON 响应(以为我不知道他们的网站如何执行查询,我猜它是 php)。现在我正尝试在 Android 中做同样的事情:

  private StringBuilder inputStreamToString(InputStream is) {
       //this method converts an inputStream to String representation
    String line = "";
    StringBuilder total = new StringBuilder();

    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return total;
}

这就是我提出请求的方式:

 public void postData(String url, String name) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    //qname is a String containing a correct player name
        nameValuePairs.add(new BasicNameValuePair("player", qname));
        nameValuePairs.add(new BasicNameValuePair("opt", "all"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        //test is just a string to check the result, which should be in JSON format
        test = inputStreamToString(response.getEntity().getContent())
                .toString();

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
}

我在“测试”字符串中得到的不是 JSON,而是某些 bf3stats 页面的完整 HTML 标记。我的请求可能有什么问题?

最佳答案

您需要在请求 header 中为要发送的数据类型设置内容类型"application/x-www-form-urlencoded"

我针对上述数据测试了您的 API,它工作正常并且我收到了大量数据作为响应。你可以找到它here .

你可以试试下面的代码:

public  String postDataToServer(String url) throws Throwable
    {

    HttpPost request = new HttpPost(url);
    StringBuilder sb=new StringBuilder();

    String requestData = prepareRequest();
    StringEntity entity = new StringEntity(requestData);
                         entity.setContentType("application/x-www-form-urlencoded;charset=UTF-8");//text/plain;charset=UTF-8
                         request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

                         request.setHeader("Accept", "application/json");
                         request.setEntity(entity); 
                         // Send request to WCF service 
                         HttpResponse response =null;
                         DefaultHttpClient httpClient = new DefaultHttpClient();
                         //DefaultHttpClient httpClient = getNewHttpClient();
                         HttpConnectionParams.setSoTimeout(httpClient.getParams(), 10*1000); 
                         HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),10*1000); 
                         try{

                         response = httpClient.execute(request); 
                         }
                         catch(SocketException se)
                         {
                             Log.e("SocketException", se+"");
                             throw se;
                         }
                         /* Patch to prevent user from hitting the request twice by clicking 
                          * the view [button, link etc] twice.
                          */
                         finally{
                         }



    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while((line = reader.readLine()) != null){
        sb.append(line);

    }
    Log.d("response in Post method", sb.toString()+"");
    return sb.toString();
    }

    public String prepareRequest()
    {

        return "player=Zer0conf&opt=all";
    }

编辑:您的 Web 服务出现错误 Expectation Failed error- 417。所以我们需要在我们的请求中添加一个参数。它是 request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);。我已经用这个更新了上面的代码。现在它工作正常。

响应看起来像这样。

希望这会有所帮助。

干杯
N_JOY

关于android - 执行 http POST 返回 HTML 而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646036/

有关android - 执行 http POST 返回 HTML 而不是 JSON的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  4. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  5. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  6. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  7. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  8. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  9. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  10. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

随机推荐