Java에서 JSON을 사용하는 HTTP POST


188

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

URL이 www.site.com

예를 들어 {"name":"myname","age":"20"}레이블이 붙은 값을받습니다 'details'.

POST 구문을 작성하는 방법은 무엇입니까?

또한 JSON Javadocs에서 POST 메소드를 찾지 못하는 것 같습니다.

답변:


167

해야 할 일은 다음과 같습니다.

  1. Apache HttpClient를 받으면 필요한 요청을 할 수 있습니다.
  2. HttpPost 요청을 작성하고 "application / x-www-form-urlencoded"헤더를 추가하십시오.
  3. JSON을 전달할 StringEntity를 작성하십시오.
  4. 전화를 실행

코드는 대략 다음과 같습니다 (여전히 디버그하여 작동시켜야합니다)

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

9
문자열에서 직접 수행하는 것처럼 JSONObject로 추상화하는 것이 좋습니다. 문자열을 잘못 프로그래밍하여 구문 오류가 발생할 수 있습니다. 된 JSONObject를 사용하여 당신은 당신의 직렬화가 항상 올바른 JSON 구조에 따라되어 있는지 확인
— 모모

3
원칙적으로, 그들은 단지 데이터를 전송하고 있습니다. 유일한 차이점은 서버에서 처리하는 방법입니다. 키-값 쌍이 거의없는 경우 key1 = value1, key2 = value2 등의 일반 POST 매개 변수로 충분할 수 있지만 데이터가 더 복잡하고 특히 복잡한 구조 (중첩 된 오브젝트, 배열)를 포함하면 JSON 사용을 고려하십시오. 키-값 쌍을 사용하여 복잡한 구조를 전송하는 것은 서버에서 매우 어려워 구문 분석하기가 어렵습니다 (시도 할 수 있으며 즉시 볼 수 있습니다). 우리가 그 일을해야했던 날을 아직도 기억하십시오. 예쁘지 않았습니다 ..
— momo

1
기쁘다! 이것이 당신이 찾고있는 것이라면, 비슷한 질문을 가진 다른 사람들이 그들의 질문을 잘 이끌어 낼 수 있도록 대답을 받아 들여야합니다. 답변에 확인 표시를 사용할 수 있습니다. 더 궁금한 점이 있으면 알려주세요
— momo

12
컨텐츠 유형이 'application / json'이 아니어야합니다. 'application / x-www-form-urlencoded'는 문자열이 쿼리 문자열과 유사하게 형식화됨을 의미합니다. NM 당신이 한 것을 보았습니다 .json blob을 속성 값으로 넣습니다.
— Matthew Ward

1
더 이상 사용되지 않는 부분은 .close ()-메소드를 제공하는 CloseableHttpClient를 사용하여 대체해야합니다. 참조 stackoverflow.com/a/20713689/1484047
— Frame91

92

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;

1
안녕하세요, httpClient 객체는 어떻게 만드나요? 인터페이스입니다
— user3290180

1
예, 인터페이스입니다. 'HttpClient httpClient = new DefaultHttpClient ();'를 사용하여 인스턴스를 만들 수 있습니다.
— Prakash

2
더 이상 사용되지 않으므로 HttpClient를 사용해야합니다. httpClient = HttpClientBuilder.create (). build ();
— user3290180

5
HttpClientBuilder를 가져 오는 방법은 무엇입니까?
— Esterlinkof

3
StringUtils 생성자에서 ContentType 매개 변수를 사용하고 수동으로 헤더를 설정하는 대신 ContentType.APPLICATION_JSON을 전달하는 것이 약간 더 깨끗합니다.
— TownCube

47

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

20

HttpURLConnection 을 사용하는 것이 가장 쉽습니다 .

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

JSONObject 또는 JSON을 구성하는 데는 아무것도 사용하지만 네트워크를 처리하지는 않습니다. 직렬화 한 다음 HttpURLConnection에 전달하여 POST에 전달해야합니다.


JSONObject j = 새로운 JSONObject (); j.put ( "name", "myname"); j.put ( "나이", "20"); 그렇게 요? 직렬화하려면 어떻게합니까?
— asdf007

@ asdf007 그냥 사용하십시오 j.toString().
— Alex Churchill

사실,이 연결이 차단되고 있습니다. POST를 보내는 경우에는 큰 문제가되지 않습니다. 웹 서버를 운영한다면 훨씬 더 중요합니다.
— Alex Churchill

HttpURLConnection 링크가 종료되었습니다.
— Tobias Roland

json을 본문에 게시하는 방법을 예제로 게시 할 수 있습니까?

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

7
코드의 기능과 문제를 해결하는 이유에 대한 설명을 추가하려면 게시물을 수정하십시오. (이 일하고 경우에도) 대부분은 단지 코드가 포함 된 대답은 일반적으로 자신의 문제를 이해하기 위해 OP 도움이되지 않습니다
— Reeno

14

이 코드를 사용해보십시오 :

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

감사! 귀하의 답변 만 인코딩 문제를 해결했습니다 :)
— Shrikant

@SonuDhakar 왜 당신 application/json이 수락 헤더와 컨텐츠 유형으로 둘 다를
— 보내는가

DefaultHttpClient더 이상 사용되지 않는 것 같습니다 .
— sdgfsdh

11

이 질문은 Java 클라이언트에서 Google Endpoints로 게시 요청을 보내는 방법에 대한 솔루션을 찾고 있습니다. 위의 답변은 아마도 정확하지만 Google Endpoints의 경우 작동하지 않습니다.

Google 엔드 포인트를위한 솔루션.

  1. 요청 본문에는 이름 = 값 쌍이 아닌 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();
    }

    HttpClient를 사용하여 수행 할 수도 있습니다.


8

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

중요한 것은 ContentType.APPLICATION_JSON을 추가하는 것입니다. 그렇지 않으면 새 StringEntity (payload, ContentType.APPLICATION_JSON)가 작동하지 않습니다.
— Johnny Cage

2

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에서 게시자를 사용할 수 있습니다. Jackson을 사용하여 JSON을 String 또는 IS로 변환


1

아파치 httpClient 4와 자바 8

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

0

아파치 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);

사용하기 전에 읽은 문서를 추천합니다.


왜 가장 많이 찬성 한 위의 답변을 통해 이것을 제안합니까?
— Jeryl Cook

응답과 함께 사용하고 조작하는 것이 매우 간단하기 때문입니다.
— Beno Arakelyan
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.