public class PrimeServerSideServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
processRequest(req, resp);
String user = req.getParameter("id0");
int primeNumberCounter = 1;
long upperLimit = 10000000;
//resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
while (++i <= upperLimit) {
long i1 = (long) Math.ceil(Math.sqrt(i));
boolean isPrimeNumber = false;
while (i1 > 1) {
if ((i != i1) && (i % i1 == 0)) {
isPrimeNumber = false;
break;
} else if (!isPrimeNumber) {
isPrimeNumber = true;
}
--i1;
}
if (isPrimeNumber) {
writer.write(String.valueOf(i));
writer.write("\n");
++primeNumberCounter;
}
writer.flush();
}
writer = resp.getWriter();
writer.write("value" + user);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp)throws IOException {
// TODO Auto-generated method stub
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doPost(req, resp);
}
}
Android端密码
private String s;
EditText numDisplay;
Button calculateNow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numDisplay= (EditText)findViewById(R.id.editText1);
calculateNow = (Button)findViewById(R.id.button1);
//s=numDisplay.toString();
calculateNow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
{
new MyAsyncTask().execute(numDisplay.getText().toString());
} }
} );
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8888");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id0", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}}}
使用post和servlet端从android端发送一个整数值,计算用户输入的值的素数。
但是我在servlet中打印用户的值时得到null值。我在android和服务器端都使用了post方法我得到错误“http get不支持这个url”,我更改了servlet端代码获取值通过get方法和get中的post方法调用。
我通过帖子发送我的数据,请求类型得到了尽管我正在使用post.I谷歌很多这个上下文但没有得到任何解决方案。 我没有得到响应只发送请求。任何帮助赞赏。