如何将用户名和密码发送到服务器并使用Android中的httpclient从服务器获取响应?我研究过很多网站,但找不到我想要的东西。
答案 0 :(得分:9)
创建一个类适配器并放置此代码...这里我假设您使用的是json webService。
public String login(String uname, String password)
{
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("Your Url");
nameValuePairs.add(new BasicNameValuePair("emailid", uname));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
is.close();
result = sb.toString();
Log.v("log","Result: " + result);
}
catch (Exception e)
{
Log.v("log", "Error converting result " + e.toString());
}
return result;
}
并拨打这样的电话......
Adapter adb = new Adapter();
response = adb.login(edtLoginemail.getText().toString(), edtLoginPassword.getText().toString());
答案 1 :(得分:0)
试试这可能对你有帮助。
userId = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<login><User>" + userId + "</User>"
+ "<Password>" + password + "</Password></login>";
serverCall(xml);
serverCall(xml);
private void serverCall(final String xml )
{
ConnectivityManager conMan = ( ConnectivityManager ) getSystemService( Context.CONNECTIVITY_SERVICE );
if( conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected() )
{
result = new Connection().getResponse("http://localhost/login.php" , xml);
if(result.equals("yes") {
//registration done
} else {
//failed
}
}
}
Connection.java
public String getResponse(String connUrl, String xml) {
DefaultHttpClient httpClient = null;
try {
MultipartEntity mp = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpPost method = new HttpPost(connUrl);
method.setEntity(mp);
mp.addPart("xml_request", new StringBody(xml));
httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(method);
if(response.getStatusLine().getStatusCode() == 200){
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
return outstream.toString();
}
}
catch(Exception e) {
Log.v("APP", "Exception while create connection for getResponse from server with: " + e.getMessage());
}
finally {
httpClient.getConnectionManager().shutdown();
}
return "";
}
答案 2 :(得分:0)
您必须在服务器端上制作网络服务。
然后,至少有两种方法可以将数据发送到服务器并从您的代码中获取响应。搜索HttpPost
&amp; HttpUrlConnection
。第一种方法更容易使用 POST 方法发送数据,但也更慢。