[英]How to send JSON raw via POST Request on Android API Level 22
目前,我正在調試我的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 */
}
}
我的問題:
我認為問題是:
確定,現在我知道了。請求HTTP類型請求必須在AsyncTask上。 不在當前線程上,因為由於網絡線程異常而在異步類上時,它將拋出異常。 我忘記了所謂的異常。 我只是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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.