2011-08-24 39 views
132

Tôi muốn tạo một HTTP POST đơn giản bằng cách sử dụng JSON trong Java.HTTP POST bằng cách sử dụng JSON trong Java

Hãy nói rằng URL là www.site.com

và phải mất trong giá trị {"name":"myname","age":"20"} dán nhãn là 'details' ví dụ.

Tôi sẽ tạo cú pháp cho POST như thế nào?

Tôi cũng không thể tìm thấy phương thức POST trong JSON Javadocs.

Trả lời

19

Có lẽ dễ nhất là sử dụng HttpURLConnection.

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

Bạn sẽ sử dụng JSONObject hoặc bất cứ điều gì để xây dựng JSON của bạn, nhưng không phải để xử lý mạng; bạn cần phải tuần tự hóa nó và sau đó chuyển nó đến một HttpURLConnection để POST.

+0

JSONObject j = new JSONObject(); j.put ("name", "myname"); j.put ("tuổi", "20"); Như vậy? Làm thế nào để tôi serialize nó? – asdf007

+0

@ asdf007 chỉ cần sử dụng 'j.toString()'. –

+0

nhưng kết nối này không đồng bộ .... nghi thức? – gumuruh

132

Dưới đây là những gì bạn cần làm:

  1. Lấy Apache HttpClient, điều này sẽ cho phép bạn thực hiện các yêu cầu cần thiết
  2. Tạo một yêu cầu HttpPost với nó và thêm tiêu đề "application/x- www-form-urlencoded"
  3. Tạo một StringEntity rằng bạn sẽ vượt qua JSON để nó
  4. Thực hiện các cuộc gọi

Th mã e gần giống như (bạn sẽ vẫn cần phải gỡ lỗi và làm cho nó hoạt động)

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

Siêu. Điều này trông khá giống như những gì tôi sẽ cần phải viết. Tôi đang cố gắng xem Apache HttpClient tại địa chỉ hc.apache.org/httpclient-3.x/ nhưng dường như nó không hoạt động? Hmph. – asdf007

+0

Vì vậy, tôi có thực sự không cần JSONObject không? Tôi có thể chỉ cần nhập chuỗi trực tiếp vào StringEntity như được hiển thị ở trên và sử dụng? – asdf007

+6

Bạn có thể thực hành tốt để trừu tượng hóa nó dưới dạng JSONObject như thể bạn đang làm trực tiếp trong chuỗi, bạn có thể lập trình chuỗi sai và gây ra lỗi cú pháp. Bằng cách sử dụng JSONObject bạn đảm bảo rằng tuần tự hóa của bạn luôn tuân theo cấu trúc JSON đúng – momo

29

@ câu trả lời của momo cho Apache HttpClient, phiên bản 4.3.1 hoặc mới hơn. Tôi đang sử dụng JSON-Java để xây dựng đối tượng JSON của tôi:

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

cảm ơn, nhưng thay vì "application/x-www-form-urlencoded", loại nội dung nên là "ứng dụng/json"! –

68

Bạn có thể tận dụng thư viện Gson để chuyển đổi các lớp học java của bạn để đối tượng JSON.

Tạo một lớp POJO cho các biến mà bạn muốn gửi theo trên Ví dụ

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

trở thành

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

khi bạn thiết lập các biến trong lớp pojo1 bạn có thể gửi rằng việc sử dụng đoạn mã sau

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

và đây là hàng nhập khẩu

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; 

và cho GSON

import com.google.gson.Gson; 
+0

hi, làm thế nào để bạn tạo đối tượng httpClient của bạn? Đó là một giao diện – user3290180

+1

Có đó là một Giao diện. Bạn có thể tạo một cá thể bằng cách sử dụng 'HttpClient httpClient = new DefaultHttpClient();' – Prakash

+1

hiện không được dùng nữa, chúng ta phải sử dụng HttpClient httpClient = HttpClientBuilder.create(). Build(); – user3290180

10

Hãy thử mã này:

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

Cảm ơn! Chỉ câu trả lời của bạn đã giải quyết được vấn đề về mã hóa :) – Shrikant

+0

@SonuDhakar tại sao bạn gửi 'application/json' cả hai làm tiêu đề chấp nhận và dưới dạng kiểu nội dung –

+0

Dường như' DefaultHttpClient' không được chấp nhận. – sdgfsdh

5

Tôi tìm thấy câu hỏi này tìm kiếm giải pháp về làm thế nào để gửi bài yêu cầu từ khách hàng java để Google thiết bị đầu cuối. Câu trả lời ở trên, rất có thể đúng, nhưng không hoạt động trong trường hợp của Google Endpoints.

Giải pháp cho điểm cuối của Google.

  1. Yêu cầu nội dung chỉ được chứa chuỗi JSON chứ không phải tên cặp = giá trị.
  2. Tiêu đề loại nội dung phải được đặt thành "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(); 
    } 
    

    Bạn cũng có thể thực hiện bằng cách sử dụng HttpClient.

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

Vui lòng xem xét chỉnh sửa bài đăng của bạn để thêm giải thích thêm về mã của bạn và tại sao nó sẽ giải quyết vấn đề. Một câu trả lời mà hầu hết chỉ chứa mã (ngay cả khi nó hoạt động) thường sẽ không giúp OP hiểu được vấn đề của họ – Reeno

+1

Điều này làm việc cho tôi, cảm ơn! – Lozzano

+0

bạn được chào đón – Mohamed

0

tôi khuyên bạn nên http-request xây dựng trên api http apache.

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

Nếu bạn muốn gửi JSON theo yêu cầu của cơ thể bạn có thể:

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

tôi higly khuyên tài liệu đọc trước khi sử dụng.

Các vấn đề liên quan