[java] Java에서 JSON을 사용하는 HTTP POST

Java에서 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. 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(); 
}


답변

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


답변

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

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

JSONObject 또는 JSON을 구성하는 데는 아무것도 사용하지만 네트워크를 처리하지는 않습니다. 직렬화 한 다음 HttpURLConnection에 전달하여 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 엔드 포인트를위한 솔루션.

  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를 사용하여 수행 할 수도 있습니다.