如何使用http post方法设置标头

时间:2011-08-17 11:44:41

标签: android

我目前正在处理一个应用程序.. 在该应用程序中,我必须使用get和post两种方法.. get方法正常工作,但在post方法中突然得到响应,如

   "invalid method.post required"..

我的代码是:

     String list_url = "************************";
    try {

        String appand = TimeStampForAuth.TimeStameMethod(main.this);
        String auth = android.util.Base64.encodeToString(("iphone" + ":" + 
            "2a5a262d5a")
        .getBytes("UTF-8"), android.util.Base64.NO_WRAP);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(list_url+appand);

        Log.d("URL_LIST", list_url+appand);

        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("login",Login));
        nvps.add(new BasicNameValuePair("password",password));
        nvps.add(new BasicNameValuePair("title",title));
        nvps.add(new BasicNameValuePair("category_id",cat_id));




        UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
        post.addHeader("Authorization", "Basic " + auth);
        post.setEntity(p_entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        String s = EntityUtils.toString(responseEntity);
        Log.d("List response", s);

    }
    catch(Exception e){
        System.out.println(e.toString());
    }

因为我错过了某些东西或者我不知道的东西......所有这些东西对于post方法都有效....

请尽快帮助我......

感谢你.........

3 个答案:

答案 0 :(得分:1)

尝试使用setHeader()代替addHeader()

答案 1 :(得分:1)

您可以尝试使用适用于Android的HttpClient 4.1:http://code.google.com/p/httpclientandroidlib/ (Android使用的HttpClient 4.0版中存在漏洞。) 您还可以使用httpClient.log.enableDebug(true);

进行更多调试

如果您不想使用外部库,我将开始调试网络流量。 使用名为Wireshark的软件,您可以非常查看和检查所有Http请求/响应 容易。

对于授权,我个人会使用:

httpClient.getCredentialsProvider().setCredentials(
  new AuthScope(hostname, port), 
  new UsernamePasswordCredentials(user, pass));

答案 2 :(得分:-1)

改为使用:

   HttpURLConnection connection = (HttpsURLConnection) serviceURL.openConnection();
   connection.setRequestMethod("POST");