我是程序世界中的每个新手,我遇到一个问题,我的要求与使用JAVA Code在Android平板电脑与台式机之间的通信有关。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
上面的代码是我的servlet代码,它在我的本地系统服务器(Tomcat
6.0)中运行,在这里,我正在通过println发送消息,并且我想在另一个系统中运行的Android应用中显示相同的消息。现在,我要发布在另一个系统上运行的android代码。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity3 extends Activity implements
OnClickListener {
Button button;
TextView outputText;
public static final String URL =
"http://192.168.0.2:9999/HttpGetServlet/HelloWorldServlet";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
@Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}}
这里的192.68.0.2是我的本地系统中正在运行servlet代码的系统的IP地址(Tomcat6.0服务器的端口号为9999)。但是它对我不起作用。两个系统都在同一个wifi网络中。非常感激。在此先感谢所有人
试试这个,我会为你工作。这是Android代码
protected Integer doInBackground(String... arg0) {
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable() {
@Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient.executeHttpPost("http://XXX.168.1.X:5555/LoginServlet/loginservlet.do", postParameters);
res = response.toString();
System.out.println("response :"+res);
} catch (Exception e) {
// e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
try {
}catch (Exception e) {
error.setText(e.getMessage());
// e.printStackTrace();
}
return null;
}
现在这是Android的另一个类
public class SimpleHttpClient {
public static String result="";
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
// String str1= request.setEntity(formEntity);
System.out.println("actual request"+formEntity);
HttpResponse response = client.execute(request);
System.out.println("response in class"+response);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}catch(Exception e){
e.printStackTrace();
System.out.println("catch");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
String result="";
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}
catch(Exception e){
e.printStackTrace();
System.out.println("catch2");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}}
最后,这是适合您的servlet代码
public class LoginServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String un,pw;
un=request.getParameter("username");
pw=request.getParameter("password");
System.out.println("username :"+un);
System.out.println("password :"+pw);
if(un.equals("") || pw.equals("") ){
out.print("null");
}
else if(un.equalsIgnoreCase("hello") && pw.equals("world"))
{
out.print("success");
}
else{
out.print("failed");
}
System.out.println("after :");
request.getAttribute("USER"+un);
request.getAttribute("PASS"+pw);
RequestDispatcher rd=request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}catch(Exception e){
System.out.println("inside exception");
e.printStackTrace();
}
finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}}
问题内容: 在Windows上,我们有一个C ++应用程序来启动Java进程。这两个应用程序需要彼此通信(通过xml片段)。 您将选择哪种进程间通信方法,为什么? 我们桌上的方法是:共享文件,管道和套接字(尽管我认为这有一些安全问题)。我愿意接受其他方法。 问题答案: 我不确定为什么您认为基于套接字的通信会带来安全隐患(使用SSL)。假设您具有明确定义的通信协议,这通常是一种非常好的方法,因为它与
目前我有一个设置,我的客户机(web应用程序,iOS应用程序等)通过REST调用与我的后端API.NET web应用程序(Nancy)对话。没什么特别的. 我现在需要将这个API拆分为微服务,每个服务可以单独升级/部署。 我的主API(公共)将只执行身份验证,然后调用我的一个微服务,它将在我的专用网络中。 在主API和其他微服务API之间有哪些不同的通信方式?每种方法的优点/缺点? 通信需要是实时
问题内容: 我有2个应用程序,一个是用C编写的,另一个是用Java编写的,它们假定在同一台机器上运行。在它们之间实施IPC的最佳方法是什么? 最好的含义是可移植性,最小的用户意识(防火墙弹出窗口…)等。 问题答案: 我将使用Sockets over loop back开始。这样,您就可以发送文本或二进制数据,并在一个进程开始或结束时彻底处理。延迟大约为20-50微秒,具体取决于您对数据进行的处理以
问题内容: Java上下文中的线程和进程之间有什么区别?用Java如何实现进程间通信和线程间通信?请给我指出一些现实生活中的例子。 问题答案: 根本的区别是线程位于相同的地址空间中,而进程位于不同的地址空间中。这意味着线程间通信是关于传递对对象的引用以及更改共享对象,而进程是关于传递对象的序列化副本。 在实践中,Java线程间通信可以实现为对共享对象进行简单的Java方法调用,并引入适当的同步。或
我正在尝试使用Android处理在Android和Arduino之间进行双向蓝牙通信。我成功地用串口将数据从Android系统传输到Arduino系统。开始(9600)。我成功地使用Arduino程序中的SoftwareSerial和蓝牙将数据从Arduino传输到Android。开始(9600)代替串行。开始(9600)。 然而,当试图使用蓝牙将数据从Android传输到Arduino时。x命令
我想在主类和控制器类之间进行阶段通信,以便可以从控制器类中的代码拖动阶段。做这件事最有效的方法是什么? Main.java: 控制器.java: FXML: