How To Send a String to a Http Server (Java)

2019-09-19 17:47发布

问题:

I have a simple http server and I need to send a String over a Stream. However, the String contains spaces and I know how to write it from client on the Stream. How can I receive it on the Server side?

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();
                }

回答1:

You can try following code:

    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();
    }

You can specify IP and port of your server. And can send any data as a parameter.



回答2:

You can use some rest client APIs like Jersey Client.

for example for send get parameter:

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();

      }

    }
}

for parse post or get method parameters use these functions:

  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;
    }
}


标签: java http