簡體   English   中英

Java服務器處理客戶端請求並對其進行響應?

[英]Java server to handle Client requests and respond to it?

我正在尋找創建Java Server來處理客戶端請求並對其進行響應的概念,我想使用不允許Socket連接的Google App引擎,那么在這種情況下客戶端和服務器是否可以使用Http請求進行通信? 如果有人可以向我闡明邏輯並提供幾行代碼,我將非常高興。

謝謝

簡單框架可能會提供您想要的東西。 它允許您以相對較少的開銷將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不僅是可嵌入的,而且是開源的,完全自包含的並且始終是異步的。 祝好運!

感謝所有答案,但我需要一種簡單的方法在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();
}

該代碼來自此站點 ,您不需要任何其他Jar文件即可在Android中使用它,並且我將其與Google App引擎一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM