执行 http POST 返回 HTML 而不是 JSON

问题描述 投票:0回答:2

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

我必须使用 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) {

    }
}

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

enter image description here

android json http-post
2个回答
14
投票

您需要在请求标头中为要发送的数据类型设置内容类型

"application/x-www-form-urlencoded"

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

您可以尝试以下代码:

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 服务出现错误 期望失败错误 - 417。所以我们需要在请求中添加一个参数。是

request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
。我已经用这个更新了上面的代码。现在效果很好。

响应看起来像这样。

Response looks something like this.


0
投票

尝试在浏览器中查看url,我相信有一个!DOCTYPE声明,它肯定无法解析为JSON对象。

© www.soinside.com 2019 - 2024. All rights reserved.