异步HTTP POST Android中

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

我工作的一个小的测试应用程序,与我的网站进行通信。它与凭据的HttpPost,以查看是否在用户注册。

然而,由于某种原因,是后发instantaniously即使它应该采取第二个它总是空的。这是我在一年前使用了大约一个班,正在当时的情况。

private class LoginTask extends AsyncTask<String, Integer, String> {

    private HashMap<String, String> mData = null;// post data
    public String serverResult = "";
    /**
     * constructor
     */
    public LoginTask(HashMap<String, String> data) {
        mData = data;
    }

    /**
     * background
     */
    @Override
    protected String doInBackground(String... params) {
        byte[] result = null;
        String str = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
        try {
            // set up post data
            ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            Iterator<String> it = mData.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
            }

            post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                result = EntityUtils.toByteArray(response.getEntity());
                str = new String(result, "UTF-8");
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
        }
        serverResult = str;
        return str;
    }

    /**
     * on getting result
     */
    @Override
    protected void onPostExecute(String result) {
        serverResult = result;
        pb.setVisibility(View.GONE);

        if(serverResult == "no")
        {
            Toast t = Toast.makeText(MainActivity.this, "Login failed. Correct username or password", Toast.LENGTH_LONG);
            t.show();
        }
        else if (serverResult.contains("email"))
        {
            Toast t = Toast.makeText(MainActivity.this, "HELLOOOOO", Toast.LENGTH_LONG);
            t.show();
        }
        else    
        {
            Toast t = Toast.makeText(MainActivity.this, "Server error: " + serverResult, Toast.LENGTH_LONG);
            t.show();
        }
    }

    protected void onProgressUpdate(Integer... progress) {
        pb.setProgress(progress[0]);
    }
}

发送到服务器的信息是完全正确和应该检索某些消息发回,但在这里它总是空的。也许东西在后台进程是错误的。

java android eclipse http-post
1个回答
1
投票

这是怎么回事在logcat的?你有什么exception吗?

而你添加Internet权限到您的清单?

<uses-permission android:name="android.permission.INTERNET" />
© www.soinside.com 2019 - 2024. All rights reserved.