[英]How to send request from android to servlet with parameters
我正在嘗試使用參數將參數從我的android設備發送到servlet,並且參數作為請求的一部分發送。
我有一個單擊按鈕,我從editText視圖獲取文本,修改我的url以使其帶有參數的url並將該url發送到AsyncTask。
這是我的代碼。
buttonRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String stringUrl = "http://192.168.11.4:8084/WebApplication1/DemoServlet?email=" + editTextEmail.getText() + "&password=" + editTextPassword.getText() + "&phone=" + editTextPhoneNumber.getText();
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new RegistrationTask().execute(stringUrl);
} else {
Toast.makeText(RegisterActivity.this, "Error!. Please check your internnet connection", Toast.LENGTH_SHORT).show();
}
}
});
}
這是我的RegistrationTask代碼。
class RegistrationTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
return getResponse(params[0]);
}
@Override
protected void onPostExecute(String result) {
editTextEmail.setText(result);
}
public String getResponse(String myurl) {
InputStream is = null;
String contentAsString = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d("Download", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
contentAsString = readIt(is, len);
return contentAsString;
} catch (Exception e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return contentAsString;
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
我嘗試調試我的servlet代碼,但請求以email = password = phone =的形式出現
請幫我整理一下。
沒有答案,但是會幫助您。
首先請也分享servlet代碼
URLEncoder.encode(arg:String):String
編碼參數,例如
String stringUrl = "http://192.168.11.4:8084/WebApplication1/DemoServlet?email="
+URLEncoder.encode(editTextEmail.getText())
readIt(stream:InputStream,len:int):String
您的方法readIt(stream:InputStream,len:int):String
不可靠。
請注意,即使有太多可用數據, InputStream.read(buf::byte[]):int
也不會填滿整個緩沖區,並且int響應指示已將數據數量寫入緩沖區,因此您的代碼將獲取數據不一致。
您可以使用DataInputStream.readFully(buff:byte[]):void
,它會完全填充緩沖區,或者在數據不足時引發異常。
或者更好的方式讀取直到EOS,其中read()
方法返回-1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.