source

Java에서 JSON을 사용한HTTP POST

goodcode 2022. 8. 17. 23:46
반응형

Java에서 JSON을 사용한HTTP POST

자바에서 JSON을 사용하여 간단한 HTTP POST를 만들고 싶습니다.

예를 들어 URL은www.site.com

그리고 그 가치를 받아들인다.{"name":"myname","age":"20"}라고 라벨이 붙은.'details'예를들면.

POST 구문을 작성하려면 어떻게 해야 하나요?

JSON Javadocs에서도 POST 메서드를 찾을 수 없는 것 같습니다.

필요한 것은 다음과 같습니다.

  1. Apache 가져오기HttpClient이를 통해 필요한 요청을 할 수 있습니다.
  2. 작성하다HttpPost그것을 사용하여 요청하고 헤더를 추가합니다.application/x-www-form-urlencoded
  3. 작성하다StringEntityJSON을 건네주겠다고 합니다.
  4. 콜을 실행하다

코드는 대략 다음과 같습니다(디버깅하여 동작시킬 필요가 있습니다).

// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
    // @Deprecated httpClient.getConnectionManager().shutdown(); 
}

Gson 라이브러리를 사용하여 Java 클래스를 JSON 개체로 변환할 수 있습니다.

위와 같이 보낼 변수에 대한 pojo 클래스를 만듭니다. 예

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

된다

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

pojo1 클래스에 변수를 설정하면 다음 코드를 사용하여 전송할 수 있습니다.

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

그리고 이것들은 수입품이다.

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;

및 GSON의 경우

import com.google.gson.Gson;

Apache HttpClient 버전 4.3.1 이후에 대한 @momo의 답변입니다.사용하고 있다JSON-JavaJSON 오브젝트를 빌드하려면:

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

아마도 Http를 사용하는 것이 가장 쉬울 것이다.URL 연결

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

JSONObject 등을 사용하여 JSON을 구축하지만 네트워크를 처리하지는 않습니다.네트워크를 시리얼화한 후 Http에 전달해야 합니다.URL POST에 접속합니다.

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

다음 코드를 사용해 보십시오.

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

Java 클라이언트에서 Google Endpoints로 게시 요청을 보내는 방법에 대한 해결책을 찾고 있습니다.위의 답변은 매우 정확하지만 Google Endpoints의 경우에는 작동하지 않습니다.

Google Endpoints용 솔루션.

  1. 요청 본문은 name=값 쌍이 아닌 JSON 문자열만 포함해야 합니다.
  2. 콘텐츠 유형 헤더는 "application/json"으로 설정해야 합니다.

    post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
                       "{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
    
    
    
    public static void post(String url, String json ) 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(json.getBytes(charset));
      }
    
      InputStream response = connection.getInputStream();
    }
    

    물론 Http Client를 사용해도 가능합니다.

Apache HTTP에는 다음 코드를 사용할 수 있습니다.

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

response = client.execute(request);

또한 json 객체를 생성하여 다음과 같이 객체에 필드를 넣을 수 있습니다.

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

Java 11 에서는, 새로운 HTTP 클라이언트를 사용할 수 있습니다.

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

퍼블리셔를 사용할 수 있습니다.InputStream,String,File. JSON의 변환String또는IS잭슨과 함께 할 수 있어요

Java 8(apache httpClient 4 포함)

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");


String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";

        try {
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            // set your POST request headers to accept json contents
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            try {
                // your closeablehttp response
                CloseableHttpResponse response = client.execute(httpPost);

                // print your status code from the response
                System.out.println(response.getStatusLine().getStatusCode());

                // take the response body as a json formatted string 
                String responseJSON = EntityUtils.toString(response.getEntity());

                // convert/parse the json formatted string to a json object
                JSONObject jobj = new JSONObject(responseJSON);

                //print your response body that formatted into json
                System.out.println(jobj);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {

                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

apache http api를 기반으로 구축된http-request를 추천합니다.

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

보내려면JSON다음 작업을 수행할 수 있습니다.

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

사용하기 전에 설명서를 읽는 것이 좋습니다.

HTTP/2 및 Web Socket을 실장하는HTTP 클라이언트 API의 Java 11 표준화.java.net 에서 구할 수 있습니다.HTTP.*:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder(URI.create("www.site.com"))
            .header("content-type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();
    
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

언급URL : https://stackoverflow.com/questions/7181534/http-post-using-json-in-java

반응형