【发布时间】:2011-05-06 05:15:59
【问题描述】:
我是 Android 新手,所以我在 HTTP 请求的 JSON 解析中遇到问题。让我简要介绍一下。实际上我正在尝试登录,用户将输入“电子邮件”作为用户名和“密码”作为密码,只要他点击登录按钮,就会在 url http://excoflare.com/dev2010/bb_snet/baranzan/index.php?json=json&UM_email="+sUserName+"&UM_password="+sPassword 上发出 http 请求,如果成功Toast 消息将在同一布局上到达“欢迎用户名”。我有两个类 (i) HelloAndroid.java 和 (ii) RestJsonClient.java
HelloAndroid.java
public class HelloAndroid extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(this);
}
public void onClick(View v) {
EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
EditText passwordEditText = (EditText) findViewById(R.id.txt_password);
String sUserName = usernameEditText.getText().toString();
String sPassword = passwordEditText.getText().toString();
String address = "http://excoflare.com/dev2010/bb_snet/baranzan/index.php?json=json&UM_email="+sUserName+"&UM_password="+sPassword+"";
JSONObject json = RestJsonClient.connect(address);
/* is something missing here if yes Please HELP*/
next();
}
private void next(){
Toast.makeText(HelloAndroid.this, "Welcome username", Toast.LENGTH_SHORT).show();
}
}
RestJsonClient
public class RestJsonClient {
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONObject json = new JSONObject();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
json=new JSONObject(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
/**
*
* @param is
* @return String
*/
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
现在我只尝试使用正确/有效的电子邮件和密码,现在只有我想要的。 请帮忙。 非常感谢
【问题讨论】:
-
检查您是否在 logcat 中遇到任何异常......
-
方法
convertStreamToString返回什么?