我正在寻找创建Java Server以处理客户端请求并对其进行响应的概念,我想使用不允许Socket连接的Google App引擎,因此客户端&在这种情况下服务器将使用Http请求进行通信?如果有人能向我澄清逻辑并提供几行代码,我会很高兴。
谢谢
答案 0 :(得分:1)
The Simple Framework可能会提供您正在寻找的内容。它允许您以相对较小的开销将HTTP服务器嵌入到您的应用程序中:
import org.simpleframework.http.core.Container;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;
import org.simpleframework.http.Response;
import org.simpleframework.http.Request;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.io.PrintStream;
public class HelloWorld implements Container {
public void handle(Request request, Response response) {
PrintStream body = response.getPrintStream();
long time = System.currentTimeMillis();
response.set("Content-Type", "text/plain");
response.set("Server", "HelloWorld/1.0 (Simple 4.0)");
response.setDate("Date", time);
response.setDate("Last-Modified", time);
body.println("Hello World");
body.close();
}
public static void main(String[] list) throws Exception {
Container container = new HelloWorld();
Connection connection = new SocketConnection(container);
SocketAddress address = new InetSocketAddress(8080);
connection.connect(address);
}
}
要与其他解决方案进行比较,请注意Simple不仅可嵌入,而且是开源的,完全独立的和异步的。祝你好运!
答案 1 :(得分:0)
感谢所有答案,但我需要一个简单的方法在Android App中使用它,如下面的代码:
HTTP GET
`
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}`
HTTP POST
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://somepostaddress.com";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "kris"));
params.add(new BasicNameValuePair("pass", "xyz"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
代码来自this site,您不需要任何其他Jar文件即可在Android中使用它,我可以将其与Google App引擎一起使用。