【发布时间】:2015-11-25 15:41:33
【问题描述】:
我正在尝试从我的 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= 的形式出现
请帮我整理一下。
【问题讨论】:
-
看看 Apache HttpClient。对您的要求非常有用。
-
如果您记录“stringUrl”,那么您会看到什么?请格式化您的第一个代码块,这样我们就不必水平滚动。
标签: java android mysql servlets