a179583637
a179583637
2016-07-11 09:55
采纳率: 35.1%
浏览 1.5k
已采纳

android客户端与服务端交互数据问题

下面是我的LoginActivity
package textview.exam;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends Activity {
Button okbutton;
EditText id;
EditText pass;
String uname;

HttpClient httpClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    final ActionBar actionBar = getActionBar();
    actionBar.hide();
    httpClient=new DefaultHttpClient();
    okbutton=(Button)findViewById(R.id.ok);
    okbutton.setOnClickListener(loginokListener);
    id = (EditText)findViewById(R.id.login_id);
    pass = (EditText)findViewById(R.id.login_password);
    Button loginback=(Button)findViewById(R.id.backlogin);
    loginback.setOnClickListener(backloginListener);

}
View.OnClickListener backloginListener=new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent in = getIntent();
        in.putExtra( "result","欢迎登录家友" );
        LoginActivity.this.setResult(1, in);
        LoginActivity.this.finish();
    }
};
View.OnClickListener loginokListener=new View.OnClickListener() {
    @Override
    public void onClick(View v) {
                    // 执行输入校验
                    if (validate())  // ①
                    {
                        // 如果登录成功
                        if (loginPro())  // ②
                        {
                            Log.i("LoginServlet","1561161");
                            Intent in = getIntent();
                            in.putExtra( "result", uname );
                            LoginActivity.this.setResult(0, in);
                            LoginActivity.this.finish();

                        }
                        else
                        {
                            Toast.makeText(LoginActivity.this,
                                    "用户名或密码错误!", Toast.LENGTH_LONG).show();
                        }
                    }



    }
};
private boolean loginPro()
{
    // 获取用户输入的用户名、密码
    String uid = id.getText().toString();
    String upass = pass.getText().toString();
    try
    {
        uname=loginyanzheng(uid, upass);
        Log.i("服务器的问题"+uname,"");
        // 如果uname不为空
        if (uname!=null)
        {
            return true;
        }
    }
    catch (Exception e)
    {
        Toast.makeText(this,"服务器响应异常,请稍后重试!", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    return false;
}

// 对用户输入的用户名、密码进行校验
private boolean validate()
{
    String uid = id.getText().toString().trim();
    if (uid.equals(""))
    {
        Toast.makeText(this,"账号不许为空!", Toast.LENGTH_LONG).show();
        return false;
    }
    String upass = pass.getText().toString().trim();
    if (upass.equals(""))
    {
        Toast.makeText(this,"请输入密码!", Toast.LENGTH_LONG).show();
        return false;
    }
    return true;
}

// 定义发送请求的方法
private String loginyanzheng(String id, String pass) throws Exception
{
    // 使用Map封装请求参数
    Map<String, String> map = new HashMap<>();
    map.put("id", id);
    map.put("pass", pass);
    Log.i("按时吃饭三coin啊搜in粗偶i","1");
    // 定义发送请求的URL
    String url = HttpUtil.BASE_URL+"LoginServlet";
    Log.i("爱上擦擦实现擦拭小","2");
    // 发送请求
    return HttpUtil.postRequest(url, map);
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        Intent in = getIntent();
        in.putExtra( "result", "欢迎登录家友");
        LoginActivity.this.setResult(1, in);
        LoginActivity.this.finish();
    }
    return false;
}

//返回动画
protected void onPause() {
    super.onPause();
    overridePendingTransition(R.anim.in_from_down,
            R.anim.out_to_up);
}

}
下面是我HttpUitl
package textview.exam;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class HttpUtil
{
// 创建HttpClient对象
public static HttpClient httpClient = new DefaultHttpClient();
public static final String BASE_URL =
"http://192.168.1.88:8888/auction/android/";
/**
*
* @param url 发送请求的URL
* @return 服务器响应字符串
* @throws Exception
*/
public static String getRequest(final String url)
throws Exception
{
FutureTask task = new FutureTask(
new Callable()
{
@Override
public String call() throws Exception
{
// 创建HttpGet对象。
HttpGet get = new HttpGet(url);
// 发送GET请求
HttpResponse httpResponse = httpClient.execute(get);
// 如果服务器成功地返回响应
if (httpResponse.getStatusLine()
.getStatusCode() == 200)
{
// 获取服务器响应字符串
String result = EntityUtils
.toString(httpResponse.getEntity());
return result;
}
return null;
}
});
new Thread(task).start();
return task.get();
}

/**
 * @param url 发送请求的URL
 * @param请求参数
 * @return 服务器响应字符串
 * @throws Exception
 */
public static String postRequest(final String url
        , final Map<String ,String> rawParams)throws Exception
{
    FutureTask<String> task = new FutureTask<String>(
            new Callable<String>()
            {
                @Override
                public String call() throws Exception
                {
                    // 创建HttpPost对象。
                    HttpPost post = new HttpPost(url);
                    // 如果传递参数个数比较多的话可以对传递的参数进行封装
                    List<NameValuePair> params = new ArrayList<>();
                    for(String key : rawParams.keySet())
                    {
                        //封装请求参数
                        params.add(new BasicNameValuePair(key
                                , rawParams.get(key)));
                    }
                    // 设置请求参数
                    post.setEntity(new UrlEncodedFormEntity(
                            params, "gbk"));
                    // 发送POST请求
                    HttpResponse httpResponse = httpClient.execute(post);
                    Log.i("所发生的初三大四","按时打算");
                    // 如果服务器成功地返回响应
                    if (httpResponse.getStatusLine()
                            .getStatusCode() == 200)
                    {
                        // 获取服务器响应字符串
                        String result = EntityUtils
                                .toString(httpResponse.getEntity());
                        return result;
                    }
                    Log.i("暗示法撒旦吃撒多长","按时打算");
                    return null;
                }
            });
    new Thread(task).start();
    return task.get();
}

}
下面是我服务端Servlet代码
package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.factory.DAOFactory;

import vo.Users;

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=GBK");
    request.setCharacterEncoding("utf-8");
    Users users = new Users();
    //客户端的账号以及密码
    users.setUserid(request.getParameter("id"));    
    users.setUpwd(request.getParameter("pass"));
    try {
        if(DAOFactory.getUserDAOInstance().findLogin(users)){       
            request.getSession().setAttribute("name", users.getUname());
            //request.getRequestDispatcher("index.jsp").forward(request, response);
        //向客户端发送字符串
        response.getWriter().println("aisd");
        System.out.println("登录成功");


        }
        else{
            response.getWriter().print("对不起,用户名、密码不符合!");
            System.out.println("对不起,用户名、密码不符合!");
        }
     } catch (Exception e) {
        e.printStackTrace();
    }

}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • yu954663801
    yu954663801 2016-07-12 01:19
    已采纳

    InputStream is = null;
    try {

    // 定义获取文件内容的URL
    URL myURL = new URL("http://xxxxx/xxxx");
    // 打开URL链接

    URLConnection ucon = myURL.openConnection();

    // 使用InputStream,从URLConnection读取数据

    is = ucon.getInputStream();

    int size=is.available();
    byte[] buf=new byte[size];
    is.read(buf);
    is.close();
    String outStr=new String(buf,"utf-8");
    System.out.println(outStr);
    } catch (Exception e) {

    e.printStackTrace();
    } finally {
    try {
    if(is!=null){ is.close(); }
    } catch (Exception e2) {}
    }

    点赞 评论

相关推荐