IT-Swarm.Net

HTTP POST pomoću JSON u Java

Želio bih napraviti jednostavan HTTP POST koristeći JSON u Javi.

Recimo da je URL www.site.com

i primjerice uzima vrijednost {"name":"myname","age":"20"} označenu kao 'details'.

Kako bih počeo stvarati sintaksu za POST?

Ne mogu izgledati ni način POST u JSON Javadocsima.

167
asdf007

Evo što trebate učiniti:

  1. Nabavite Apache HttpClient, to će vam omogućiti da podnesete potreban zahtjev
  2. Pomoću njega stvorite HttpPost zahtjev i dodajte zaglavlje "application/x-www-form-urlencoded"
  3. Stvorite StringEntity kojim ćete mu prenijeti JSON
  4. Izvršite poziv

Kôd otprilike izgleda (morat ćete ga ispraviti i ukloniti program)

//Deprecated
//HttpClient httpClient = new DefaultHttpClient(); 

HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 

try {

    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);

    //handle response here...

}catch (Exception ex) {

    //handle exception here

} finally {
    //Deprecated
    //httpClient.getConnectionManager().shutdown(); 
}
154
momo

Možete koristiti Gson knjižnicu za pretvorbu svojih Java klasa u JSON objekte.

Napravite pojo klasu za varijable koje želite poslati kao u gornjem primjeru

{"name":"myname","age":"20"}

postaje

class pojo1
{
   String name;
   String age;
   //generate setter and getters
}

jednom kada postavite varijable u klasu pojo1, možete je poslati sljedećim kodom

String       postUrl       = "www.site.com";// put in your url
Gson         gson          = new Gson();
HttpClient   httpClient    = HttpClientBuilder.create().build();
HttpPost     post          = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse  response = httpClient.execute(post);

a to su uvozi

import org.Apache.http.HttpEntity;
import org.Apache.http.HttpResponse;
import org.Apache.http.client.HttpClient;
import org.Apache.http.client.methods.HttpPost;
import org.Apache.http.entity.StringEntity;
import org.Apache.http.impl.client.HttpClientBuilder;

a za GSON

import com.google.gson.Gson;
86
Prakash

@ momov odgovor za Apache HttpClient, verzija 4.3.1 ili novija. Za izradu JSON objekta koristim JSON-Java:

JSONObject json = new JSONObject();
json.put("someKey", "someValue");    

CloseableHttpClient httpClient = HttpClientBuilder.create().build();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity(json.toString());
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.close();
}
37

Vjerojatno je najlakše koristiti HttpURLConnection .

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

Koristite JSONObject ili nešto drugo za izradu vašeg JSON, ali ne za rad s mrežom; morate ga serializirati i proslijediti na HttpURLCpoveza u POST.

20
Alex Churchill
protected void sendJson(final String play, final String prop) {
     Thread t = new Thread() {
     public void run() {
        Looper.prepare(); //For Preparing Message Pool for the childThread
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit
        HttpResponse response;
        JSONObject json = new JSONObject();

            try {
                HttpPost post = new HttpPost("http://192.168.0.44:80");
                json.put("play", play);
                json.put("Properties", prop);
                StringEntity se = new StringEntity(json.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                /*Checking response */
                if (response != null) {
                    InputStream in = response.getEntity().getContent(); //Get the data in the entity
                }

            } catch (Exception e) {
                e.printStackTrace();
                showMessage("Error", "Cannot Estabilish Connection");
            }

            Looper.loop(); //Loop in the message queue
        }
    };
    t.start();
}
13
Medo

Isprobajte ovaj kôd:

HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/json");
    request.addHeader("Accept","application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);

    // handle response here...
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}
12
Sonu Dhakar

Otkrio sam ovo pitanje u potrazi za rješenjem kako poslati zahtjev za slanje od klijenta Java na Google Endpoints. Gore navedeni odgovori, vrlo vjerovatno točni, ali ne djeluju u slučaju Google Krajnjih točaka.

Rješenje za Google krajnje točke.

  1. Tijelo zahtjeva mora sadržavati samo JSON niz, a ne ime = parni vrijednost.
  2. Zaglavlje vrste sadržaja mora biti postavljeno na "application/json".

    post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
                       "{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
    
    
    
    public static void post(String url, String param ) throws Exception{
      String charset = "UTF-8"; 
      URLConnection connection = new URL(url).openConnection();
      connection.setDoOutput(true); // Triggers POST.
      connection.setRequestProperty("Accept-Charset", charset);
      connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    
      try (OutputStream output = connection.getOutputStream()) {
        output.write(param.getBytes(charset));
      }
    
      InputStream response = connection.getInputStream();
    }
    

    To sigurno možete učiniti i pomoću HttpClient-a.

8
yurin

S Apache HTTP možete koristiti sljedeći kôd:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

response = client.execute(request);

Uz to možete stvoriti json objekt i u njega staviti polja kao što je ovaj

HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
5
TMO

Preporučujem http-zahtjev izgrađen na Apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
    .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);

   int statusCode = responseHandler.getStatusCode();
   String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null. 
}

Ako želite poslati JSON kao tijelo zahtjeva, možete:

  ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);

Prije uporabe, preporučujem pročitanu dokumentaciju.

0
Beno Arakelyan

Za Java 11 možete koristiti novi HTTP klijent :

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

Izdavača možete koristiti iz InputStream, String, File. Pretvaranje JSON u gudački ili IS možete s Jacksonom.

0
user3359592