目前我正在调试我的Java代码,如下所示:
public void sign_in(View view) {
String json = "";
// The Username & Password
final EditText em = (EditText) findViewById(R.id.Username);
String email = (String) em.getText().toString();
final EditText pw = (EditText) findViewById(R.id.Password);
String password = (String) pw.getText().toString();
// -----------------------
JSONObject jsonObject = new JSONObject();
try {
HttpResponse response;
jsonObject.accumulate("email", email);
jsonObject.accumulate("password", password);
json = jsonObject.toString();
URL url = new URL("http://cloudspecinc.herokuapp.com/api/user/login/");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(json, "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");
response = httpClient.execute(httpPost);
String sresponse = response.getEntity().toString();
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
} finally {
/* nothing to do here */
}
}
我的问题:
我认为问题是:
答案 0 :(得分:7)
OK现在我知道..请求HTTP类型请求必须在AsyncTask上。不在当前线程上,因为由于网络线程异常而不在异步类上时会抛出异常。我忘记了Exception被称为什么。我只是Java的初学者。因为我不是真正的Java程序员。
以下是帮助其他人处理此类问题的代码。
public class REST extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection=null;
String json = null;
// The Username & Password
final EditText em = (EditText) findViewById(R.id.Username);
String email = (String) em.getText().toString();
final EditText pw = (EditText) findViewById(R.id.Password);
String password = (String) pw.getText().toString();
// -----------------------
try {
HttpResponse response;
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
jsonObject.accumulate("password", password);
json = jsonObject.toString();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://cloudspecinc.herokuapp.com/api/user/login/");
httpPost.setEntity(new StringEntity(json, "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");
response = httpClient.execute(httpPost);
String sresponse = response.getEntity().toString();
Log.w("QueingSystem", sresponse);
Log.w("QueingSystem", EntityUtils.toString(response.getEntity()));
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
} finally {
/* nothing to do here */
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (result != null) {
// do something
} else {
// error occured
}
}
}