为什么HttpPost不会发送任何数据?

时间:2017-06-09 20:33:06

标签: android httpclient

我有一个旧的Android应用程序,我使用了几年。有一个函数在由Async任务运行的服务器上执行post请求。

工作得很好。现在它停止了工作。我调试了很多,并意识到帖子对服务器来说是空的。服务器页面按预期工作(从其他来源发布帖子)。

我尝试更改标题,发送json,严格,urlencodedentity,没有任何作用。我不知道哪些是错的。还尝试使用HTTPUrlConnection获得相同的结果。

此处是我的代码:

    protected String PostByHttpClient(String url, List<NameValuePair> postParams) throws IOException
    {           
        // Com erro depois de uma atualização, setEntity não insere variaveis no post, por algum motivo.
        final String USER_AGENT = "Mozilla/5.0";
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 25000);
        HttpConnectionParams.setSoTimeout(httpParameters, 20000);
        HttpClient client = new DefaultHttpClient(httpParameters);
        String Params = "?"+getQuery(postParams);
        HttpPost post = new HttpPost(url/*+Params*/);

        // monta o header
        post.setHeader("User-Agent", USER_AGENT);
        //post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8");
        //post.setHeader("Accept-Language", "en-US,en;q=0.5");
        post.setHeader("Connection", "keep-alive");
        //post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        post.setHeader("Pragma", "no-cache");

        // executa submit (post)
        StringEntity entity;
        HttpResponse response = null;
        try
        {
            //entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
            entity = new StringEntity(getJSONQuery(postParams),HTTP.UTF_8);
            post.setEntity(entity);
            response = client.execute(post);
        }
        catch (Exception ex)
        {
            Log.e("SURV", ex.getMessage());
        }

        int responseCode = response.getStatusLine().getStatusCode();

        Log.i("Quest", "\nSending 'POST' request to URL : " + url);
        Log.i("Quest", "Post parameters : " + getJSONQuery(postParams));
        Log.i("Quest", "Response Code : " + responseCode);
        Log.i("Quest", "Method: " + post.getMethod());

        // código de status HTTP (2xx = sucesso)
        if (responseCode >= 300) throw new HttpResponseException(responseCode, response.getStatusLine()
                .getReasonPhrase()+" - "+url);

        // sucesso (lê o retorno da pagina)
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();

        String line = "";
        while ((line = rd.readLine()) != null)
        {
            result.append(line + System.getProperty("line.separator"));
        }

        return result.toString();       
    }

getJsonQuery将NamePairValue转换为Json(及其工作)。

有人可以帮我吗?

0 个答案:

没有答案