settHeader(“内容类型”,“”) - 混乱

时间:2014-07-30 04:56:43

标签: java php android json

我有一个函数,我想将两个变量POST到php端,在这两个变量匹配并且服务器处理结果之后,我想在JSON中返回结果。截至目前,我的set header属性如下所示:

httppost.setHeader("Content-type", "application/json");

但是在Wikipedia阅读时,我发现内容类型应该是application/x-www-form-urlencoded并且接受JSON应该是Accept: application/json我想要更清楚这一点,我该如何修改我的代码实现我想要的结果?截至目前我正在使用本地主机,我的POST变量似乎没有在php端传递。以下是我的完整功能:

public void parse(String last, String pwd){
        String lastIndex = last;
        DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams()); 
        System.out.println("URL is: "+CONNECT_URL); 
        HttpPost httppost = new HttpPost(CONNECT_URL);
        httppost.setHeader("Content-type", "application/json");
        try{

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("key", password));
            nameValuePairs.add(new BasicNameValuePair("last_index", lastIndex));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));



            System.out.println("Post variables(Key): "+password+"");
            System.out.println("Post variables(last index): "+lastIndex);




            HttpResponse resp = http.execute(httppost); 
            HttpEntity entity = resp.getEntity();
            ins = entity.getContent(); 


            BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8); 
            StringBuilder sb = new StringBuilder(); 
            String line = null; 

            while((line = bufread.readLine()) != null){
                sb.append(line +"\n"); 
            }
            result = sb.toString(); 
            System.out.println("Result: "+result); 



            //  readAndParseJSON(result);
        }catch (Exception e){
            System.out.println("Error: "+e);
        }finally{
            try{
                if(ins != null){
                    ins.close();
                }
            }catch(Exception smash){
                System.out.println("Squish: "+smash); 
            }
        }
        //  return  result; 

    }

2 个答案:

答案 0 :(得分:2)

您的代码似乎正在执行该文章描述的内容,但

除外
// httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");

您正在此处添加x-www-form-urlencoded内容

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

答案 1 :(得分:2)

您有上限问题。尝试&#34;内容类型&#34; ,而不是&#34;内容类型&#34; (或使用const HTTP.CONTENT_TYPE)。< / p>