嗨我正在为iOS和Android编写一个应用程序来与druapl站点进行交互。我试图让用户登录到网站,然后将成功登录的数据保存在应用程序的首选项中。下面我能够成功地做我想要的可可,但我一直无法使它在Java中工作。这两个代码片段都在下面。任何帮助与Java将不胜感激。Android发布变量到drupal
我只是没有得到任何回应的所有来自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();
}
}
}
它不工作?你遇到什么错误?你可以发布堆栈跟踪吗? –
我对Cocoa并不熟悉,但它看起来像在Cocoa中的请求中发送了一个字符串“username = user&password = pass”,并且在请求中使用了Java中的JSON对象。 –