1
任何人都可以帮助我如何将认证详细信息POST到宁静的Web服务并获取响应。 我必须张贴用户名,IsAuthenticated(即真或假),密码。也请解释url编码方法。 我已经在下面显示了我的代码。我是Android的初学者。如何调用Android中的Restful web服务
public class LoginActivity extends Activity
{
String Username;
String Password;
String IsAuthenticated;
String answer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
POST(Username,Password,IsAuthenticated);
} catch (Exception e) {
e.printStackTrace();
}
}
public String POST(String Username, String IsAuthenticated, String Password) {
String Returned = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://......./Authenticate");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Your DATA
nameValuePairs.add(new BasicNameValuePair("UserName", "Username"));
nameValuePairs.add(new BasicNameValuePair("IsAuthenticated", "false"));
nameValuePairs.add(new BasicNameValuePair("Password", "Password"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Returned = EntityUtils.toString(resEntity);
System.out.println(Returned);
Toast.makeText(this, Returned, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "There was an issue Try again later", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this, "There was an IO issue Try again later", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return Returned;
}
}
您的POST方法看起来不错。你有什么错误吗?但是,您应该在单独的线程中执行网络活动。请参阅[无痛线程](http://developer.android.com/resources/articles/painless-threading.html)和[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html )。 – basilisk 2011-02-17 11:29:59
嗨basilisk,我遇到麻烦是编码我的登录参数与URL.If我克服达,我会获得输出。有什么建议么??? – Dray 2011-02-17 11:54:23