2014-08-30 138 views
-1

我有一個簡單的http服務器,我需要通過Stream發送String。但是,字符串包含空格,我知道如何從Stream的客戶端寫入它。我如何在Server方接收它?如何將字符串發送到Http服務器(Java)

static class InsertPostHandler implements HttpHandler { 
    public void handle(final HttpExchange HE) throws IOException { 
    Thread thread = new Thread(new Runnable() { 
     final HttpExchange t = HE; 
      @Override 
      public void run() { 
       Statement stmt = null; 
       // add the required response header for a PDF file 
       String Request =(t.getRequestURI().toString() 
        .split("\\/@@postssystem/"))[1]; 
       System.out.println(Request); 
       if(Request.equals("createpost")){ 
       Headers h = t.getResponseHeaders(); 
       h.add("Content-Type", "Image"); 
       h.add("Cache-Control","must-revalidate"); 
       //Here I Need To Receive A String 
       try { 
        t.sendResponseHeaders(200,1); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

回答

0

你可以試試下面的代碼:

try { 
     String toSend = "message"; 
     String urlParameters = "message=" + toSend; 
     String request = "http://IP:PORT/Project/message.html"; 
     URL url = new URL(request); 

     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setInstanceFollowRedirects(false); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
     connection.setRequestProperty("charset", "utf-8"); 
     connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length)); 
     connection.setUseCaches(false); 

     DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
     wr.writeBytes(urlParameters); 

     int code = connection.getResponseCode(); 
     System.out.println(code); 
     wr.flush(); 
     wr.close(); 
     connection.disconnect(); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

您可以指定IP和服務器的port。並可以將任何數據作爲參數發送。

+0

但如何接收字符串伴侶嗎? – reza 2014-08-30 13:52:09

+0

在服務器端,您可以使用'HttpServletRequest'來獲取請求參數。 – 2014-08-31 06:18:23

0

您可以使用一些其他客戶端API,如Jersey Client

例如用於發送GET參數:

import com.sun.jersey.api.client.Client; 
import com.sun.jersey.api.client.ClientResponse; 
import com.sun.jersey.api.client.WebResource; 

public class JerseyClientGet { 



public static void main(String[] args) { 
    try { 

     Client client = Client.create(); 

     WebResource webResource = client 
      .resource("http://localhost:8080/RESTfulExample/rest/json/metallica/get"); 

     ClientResponse response = webResource.accept("application/json") 
        .get(ClientResponse.class); 

     if (response.getStatus() != 200) { 
      throw new RuntimeException("Failed : HTTP error code : " 
      + response.getStatus()); 
     } 

     String output = response.getEntity(String.class); 

     System.out.println("Output from Server .... \n"); 
     System.out.println(output); 

     } catch (Exception e) { 

     e.printStackTrace(); 

     } 

    } 
} 

用於解析post或get方法的參數使用這些功能:

private static Map<String, String> parsePostParameters(HttpExchange exchange) 
      throws IOException { 

     if ("post".equalsIgnoreCase(exchange.getRequestMethod())) { 
      @SuppressWarnings("unchecked") 
      InputStreamReader isr 
        = new InputStreamReader(exchange.getRequestBody(), "utf-8"); 
      BufferedReader br = new BufferedReader(isr); 
      String query = br.readLine(); 
      return queryToMap(query); 
     } 
     return null; 
    } 

    public static Map<String, String> queryToMap(String query) { 
     Map<String, String> result = new HashMap<>(); 
     for (String param : query.split("&")) { 
      String pair[] = param.split("="); 
      if (pair.length > 1) { 
       result.put(pair[0], pair[1]); 
      } else { 
       result.put(pair[0], ""); 
      } 
     } 
     return result; 
    } 
} 
相關問題