嗨,我正在为 iOS 和 Android 编写一个应用程序来与 druapl 站点交互。我正在尝试允许用户登录网站,然后将成功登录的数据保存在应用程序的首选项中。下面我能够在 Cocoa 中成功地做我想做的事情,但我无法让它在 Java 中工作。两个代码片段都在下面。任何有关java的帮助将不胜感激。
我只是没有从java得到任何响应,当它应该是一个长的JSON响应时,响应作为一个空字符串返回。
可可登录(工作)
NSURL *url = [NSURL URLWithString:@"http://examplesite/api/rest/user/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSData *requestBody = [[NSString stringWithFormat:@"username=%@&password=%@",[userField text],[passField text]] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
Java 登录(不工作)
class loginTask extends AsyncTask<Void, Void, Void> {
HttpResponse response;
public loginTask() {
}
@Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://examplesite/api/rest/user/login");
try {
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "password"));
post.setEntity(new UrlEncodedFormEntity (formparams));
response = client.execute(post);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Void unused) {
//TODO finish the activity
try {
Toast.makeText(Login.this, EntityUtils.toString(response.getEntity(), "UTF-8"), Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}