Java和REST POST方法 - 如何将URL POST请求转换为JSON Body POST请求?

时间:2017-06-29 15:38:03

标签: java json web-services rest post

我有完全有效的类,并成功向外部系统发送POST请求。 目前在课堂上发送的参数是:

username:maxadmin
password:sm
DESCRIPTION: REST API test

现在我想复制此类的粘贴并以这种方式对其进行转换,以便我可以使用JSON主体发送请求,但我不知道该怎么做。 我看到我应该conn.setRequestProperty("Content-Type", "application/json");而不是application/x-www-form-urlencoded

有人可以转换我的代码,以便使用JSON正文发送请求,而不是使用URL来发送参数吗? 这是我的网址'工作类(你会看到用户名/密码在URL中,而参数是在数组中发送的,我目前只有一个属性描述,我发送)

package com.getAsset;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;

public class GETAssetsPOST {


public static String httpPost(String urlStr, String[] paramName,
        String[] paramVal) throws Exception {

          URL url = new URL(urlStr);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();

          conn.setRequestMethod("POST");
          conn.setDoOutput(true);
          conn.setDoInput(true);
          conn.setUseCaches(false);
          conn.setAllowUserInteraction(false);                          
         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          OutputStream out = conn.getOutputStream();                          
          Writer writer = new OutputStreamWriter(out, "UTF-8");

          for (int i = 0; i < paramName.length; i++) {
            writer.write(paramName[i]);
            writer.write("=");
            writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
            writer.write("&");
          }
          writer.close();
          out.close();                    

          if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
          }

          // Buffer the result into a string
          BufferedReader rd = new BufferedReader(
             new InputStreamReader(conn.getInputStream()));

          StringBuilder sb = new StringBuilder();

          String line;
         while ((line = rd.readLine()) != null) {
           sb.append(line);
          }
         rd.close();
                      conn.disconnect();
          return sb.toString();
        }

public static void main(String[] args) throws Exception {       
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);

}

}

谢谢

0 个答案:

没有答案