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

时间:2018-11-16 14:48:54

标签: java rest post

我是使用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:服务器返回HTTP响应代码:401,URL:https://url_example.com/     在sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)     在sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)     在sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)     在ab.pkg.TestAuth.main(TestAuth.java:44)

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

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

5 个答案:

答案 0 :(得分:2)

我建议您从以下主题将JSON文件解析为String: How to read json file into java with simple JSON library

然后,您可以使用流行的简单库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或Objects。这只是一个例子:)

如果您想通过POST方法传递此地图,则可以遵循以下主题: Send data in Request body using HttpURLConnection

[UPDATE]正常,从服务器得到200 OK,没有异常,没有错误:

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

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

答案 1 :(得分:0)

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.

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

尝试:

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

另外,请查看以下链接的答案:Http Basic Authentication in Java using HttpClient?

答案 4 :(得分:-1)

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

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

关于发送实际请求,我想您可以看一下How to send Https Post request in java