JAVA中的HTTP POST请求,有效负载为json文件

时间:2017-10-04 08:08:35

标签: java json rest post

下面是我尝试发送HTTP POST请求,该请求将json文件作为有效负载发送。我总是得到的错误是

java.io.FileNotFoundException:test.json(系统找不到指定的文件)

尽管test.json文件位于同一文件夹中。

private void sendPost() throws Exception {`

    String url = "url";
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();

    String postData = AutomaticOnboarding.readFile("test.json");
    urlParameters.add(new BasicNameValuePair("data", postData));
    StringEntity se = new StringEntity(postData);
    post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

    post.setEntity(se);

    HttpResponse response = httpClient.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    int responseCode = response.getStatusLine().getStatusCode();
    System.out.println("Response Code : " +responseCode);
    if(responseCode == 200){
        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());
    }
}

以下是readFile方法:

public static String readFile(String filename) {
    String result = "";
    try {
        BufferedReader br = new BufferedReader(new FileReader(filename));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        result = sb.toString();
    } catch(Exception e) {
        e.printStackTrace();
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

使用类加载器获取jar内的资源

getClass().getClassLoader().getResourceAsStream(filename)