繁体   English   中英

如何使用json文件作为正文执行发布请求

[英]How to perform a post request using json file as body

我是使用REST调用的新手。 我的项目中有一个test.json文件。

该文件的内容为:

{
  "Added": {
    "type": "K",
    "newmem": {
      "IDNew": {
        "id": "777709",
        "type": "LOP"
      },
      "birthDate": "2000-12-09"
    },
    "code": "",
    "newest": {
      "curlNew": "",
      "addedForNew": ""
    }
  }
}

Java代码:

import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestAuth {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        File file = new File("test.json");
           try {
                JSONParser parser = new JSONParser();
                //Use JSONObject for simple JSON and JSONArray for array of JSON.
                JSONObject data = (JSONObject) parser.parse(
                      new FileReader(file.getAbsolutePath()));//path to the JSON file.
             System.out.println(data.toJSONString());
                URL url2 = new URL("myURL");
                HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("Authorization", "Bearer aanjd-usnss092-mnshss-928nss");

                conn.setDoOutput(true);
                OutputStream outStream = conn.getOutputStream();
                OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
                outStreamWriter.write(data.toJSONString());
                outStreamWriter.flush();
                outStreamWriter.close();
                outStream.close();
                String response = null;
                DataInputStream input = null;
                input = new DataInputStream (conn.getInputStream());
                while (null != ((response = input.readLine()))) {
                    System.out.println(response);
                    input.close ();
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
    }
}

异常:java.io.IOException:服务器在sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)处返回URL的HTTP响应代码:401: https ://url_example.com/。位于sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)的net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)位于ab.pkg.TestAuth.main(TestAuth。 Java:44)

在Soap Ui中,将Endpoint和以上内容添加为POST请求的请求正文是成功的响应。

如何读取json内容并将其作为Java中的请求正文传递?

我建议您从以下主题将JSON文件解析为String: 如何使用简单的JSON库将json文件读入java

然后,您可以使用流行的简单库Gson将JSON-String解析为Map(或您指定的任何内容)。

String myJSON = parseFileToString();  //get your parsed json as string
Type mapType = new TypeToken<Map<String, String>>(){}.getType(); //specify type of 
your JSON format
Map<String, String> = new Gson().fromJson(myJSON, mapType); //convert it to map

然后,您可以将此地图作为请求正文传递给您的帖子。 不要在POST方法中将任何JSON数据作为URL传递。 只要您不使用GET,URL中的数据就不是好主意。

您还可以将整个JSON(字符串版本)作为参数发送,而无需将其转换为Maps或Object。 这仅是示例:)

如果要在POST方法中传递此映射,则可以遵循以下主题: 使用HttpURLConnection在请求正文中发送数据

[更新]它工作正常,服务器结果200正常,没有异常,没有错误:

   package com.company;

import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestAuth {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        File file = new File("test.json");
        try {
            JSONParser parser = new JSONParser();
            //Use JSONObject for simple JSON and JSONArray for array of JSON.
            JSONObject data = (JSONObject) parser.parse(
                    new FileReader(file.getAbsolutePath()));//path to the JSON file.
            System.out.println(data.toJSONString());

            String paramValue = "param\\with\\backslash";
            String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");

            URL url2 = new URL("https://0c193bc3-8439-46a2-a64b-4ce39f60b382.mock.pstmn.io");
            HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Authorization", "Bearer aanjd-usnss092-mnshss-928nss");

            conn.setDoOutput(true);
            OutputStream outStream = conn.getOutputStream();
            OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
            outStreamWriter.write(data.toJSONString());
            outStreamWriter.flush();
            outStreamWriter.close();
            outStream.close();
            String response = null;

            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());

            DataInputStream input = null;
            input = new DataInputStream (conn.getInputStream());
            while (null != ((response = input.readLine()))) {
                System.out.println(response);
                input.close ();
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

让我知道该答案是否解决了您的问题。 问候!

我承认我快速阅读了代码,但看起来还可以。 但是,状态为401表示此服务器的url需要正确的身份验证。 https://httpstatuses.com/401

您可能需要发送有效的身份验证才能获得授权。 您的授权标头必须无效。

You can read the file in a method and pass the json string data read from the file to another method for posting the json data to the Rest end point
1) Read the Json data from the file
  public String readJsonDataFromFile() {
   InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(new 
                                                          File("sample.json")));
      StringWriter writer = new StringWriter();   
      IOUtils.copy(inputStreamReader, writer);
      return writer.toString());
  }

2) Call the Restend point passing the Json data
  public void postData(String payload) {
        String url = "http://localhost:8080/endPoint";

        // Use the access token for authentication
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(url, 
                        HttpMethod.POST, entity, String.class);
       System.out.println(response.getBody());       
}
     As the response returned is 401, it is not successfully authenticated with the rest endpoint, check the error log if it gives more info about the error like whether the access token is expired.

尝试:

    String username = "username";
    String password = "password";
    String auth=new StringBuffer(username).append(":").append(password).toString();
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
    String authHeader = "Basic " + new String(encodedAuth);
    post.setHeader("AUTHORIZATION", authHeader);

另外,请查看以下链接的答案: Java中使用HttpClient的Http基本身份验证?

如果您想读取JSON文件的内容,可以执行以下操作,假设您的JSON文件与尝试加载JSON的类位于同一包中:

InputStream stream = YourClass.class.getResourceAsStream(fileName); String result = CharStreams.toString(new InputStreamReader(stream));

至于发送实际的请求,我想您可以看看如何在Java中发送Https Post请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM