2017年5月8日 星期一

[ Java 常見問題 ] HttpClient - HTTP POST using JSON in Java

Source From Here 
Question 
I would like to make a simple HTTP POST using JSON in Java. Let's say the URL is www.site.com and it takes in the value {"name":"myname","age":"20"} labeled as 'details' for example. How would I go about creating the syntax for the POST? I also can't seem to find a POST method in the JSON Javadocs. 

How-To 
Here is what you need to do: 
1. Get the Apache HttpClient, this would enable you to make the required request
2. Create an HttpPost request with it and add the header "application/x-www-form-urlencoded"
3. Create a StringEntity that you will pass JSON to it
4. Execute the call

The code roughly looks like (you will still need to debug it and make it work): 
  1. HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead   
  2.   
  3. try {  
  4.   
  5.     HttpPost request = new HttpPost("http://yoururl");  
  6.     StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");  
  7.     request.addHeader("content-type""application/x-www-form-urlencoded");  
  8.     request.setEntity(params);  
  9.     HttpResponse response = httpClient.execute(request);  
  10.   
  11.     //handle response here...  
  12.   
  13. }catch (Exception ex) {  
  14.   
  15.     //handle exception here  
  16.   
  17. finally {  
  18.     //Deprecated  
  19.     //httpClient.getConnectionManager().shutdown();   
  20. }  
Supplement 
How to convert hashmap to JSON object in Java 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...