登录网站后的Android帖子方法

时间:2014-07-24 12:38:24

标签: android post login

我正在尝试为我家的餐厅开发一个APP,客户可以在这里进行在线购物。我们有一个可能提供的网站,所以我想做的是创建一个模拟网站POST方法的APP。

我能够成功登录网站,但之后POST方法无效。我怎么能在Android中这样做?也许是与饼干有关的东西?

我正在使用这种方法:

public String PostInternetData(String tel,String pass)抛出异常{

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://pedidos.pizzeriabritannia.com/index.asp?Opc=Pedir");
    StringBuilder data = null;
    String answer ="";
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("login", tel));
        nameValuePairs.add(new BasicNameValuePair("password", pass));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        data = inputStreamToString(response.getEntity().getContent());
        answer = data.toString();


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    return answer;

}

2 个答案:

答案 0 :(得分:1)

每次创建新的new DefaultHttpClient();

时,你的cookie都可能出现问题
  HttpClient httpclient = new DefaultHttpClient(); 

因此,您的登录信息将包含Cookie,并且会在新请求中更改HttpClient httpclient = new DefaultHttpClient();

使用lib文件httpmine-4.0.1.jar和apache-mine4j-0.6.jar

http://www.java2s.com/Code/Jar/h/Downloadhttpmime401jar.htm

http://www.java2s.com/Code/Jar/a/Downloadapachemime4j06jar.htm

创建一个类

 public class HttpClientSingalTon {

private static Object yourLock = new Object();
private static CookieStore yourCookie = null;

public static HttpClient getHttpClienttest() {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    synchronized (yourLock) {
        if (yourCookie == null) {
            yourCookie = httpClient.getCookieStore();
        } else {
            httpClient.setCookieStore(yourCookie);
        }
    }
    return httpClient;
}

}

并在你的httppost()中使用

  HttpClient httpclient ;
    httpclient = HttpClientSingalTon.getHttpClienttest();
    HttpPost httpPostRequest = new HttpPost(URL);

您的所有请求都应由

创建
   httpclient = HttpClientSingalTon.getHttpClienttest(); 

它将是所有请求的cookie .. 希望它能解决你的问题。

答案 1 :(得分:0)

最简单的方法是对服务器执行JSON请求并在Android应用中使用结果。基本上,您向Web服务器上包含数据库查询的页面发布请求,并让服务器发回结果。

请点击此处查看大量示例:-) http://localtone.blogspot.co.uk/2009/07/post-json-using-android-and-httpclient.html