Java:如果 doOutput=false,则无法写入 URLConnection - 调用 setDoOutput(true)

标签 java json rest api service

我是一名 QA,希望了解更多有关 Java 编程的知识,我遇到的问题是: 我正在尝试将员工数据发布到一些假 Rest API 的数据库中,但我得到了

Cannot write to a URLConnection if doOutput=false - call setDoOutput(true)"

到目前为止,我尝试了 StackOverflow 中的一些想法,但由于我缺乏经验,我很容易陷入更深的问题。 所以网址是:http://dummy.restapiexample.com/api/v1/create首先我创建了一个 json 对象的 Employee 类:

public class Main {

    public static void main(String[] args) {
        new Main();   
    }

    public Main() {    

        Employees em = new Employees();

        em.setEmployeeName("Alex");
        em.setEmployeeSalary("1234");
        em.setEmployeeAge("28");

        try{
            URL url = new URL("http://dummy.restapiexample.com/api/v1/create");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");  

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Unsuccessful call: HTTP error : "
                    + conn.getResponseCode());
            }     

            // URLConnection urlc = url.openConnection();
            // urlc.setDoOutput(true);

            PrintWriter pw = new PrintWriter(conn.getOutputStream());


            pw.print(new Gson().toJson(em));
            pw.close();
            pw.flush();

            BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream())
            );
            String json = "";
            String output;
            while ((output = br.readLine()) != null) {
                json += output;
            }
            conn.disconnect();               

            System.out.println("Employee name:  " + em.getEmployeeName());
        }   
        catch (MalformedURLException e) { 
            e.printStackTrace();
        }
        catch (IOException e) { 
            e.printStackTrace();        
        }
    }
}

好吧,使用您的一个想法并添加下一行代码(在上面的代码中进行了注释):

URLConnection urlc = url.openConnection();
urlc.setDoOutput(true);

所以代码如下:

public class Main {

public static void main(String[] args) {
new Main();   
}
public Main() {    

    Employees em = new Employees();

    em.setEmployeeName("Alex");
    em.setEmployeeSalary("1234");
    em.setEmployeeAge("28");

    try{
        URL url = new URL("http://dummy.restapiexample.com/api/v1/create");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");  



        if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Unsuccessful call: HTTP error : "
        + conn.getResponseCode());
       }     

        URLConnection urlc = url.openConnection();
       urlc.setDoOutput(true);

        PrintWriter pw = new PrintWriter(urlc.getOutputStream());


        pw.print(new Gson().toJson(em));
        pw.close();
        pw.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader(
        (urlc.getInputStream())));
        String json = "";
        String output;
        while ((output = br.readLine()) != null) {
        json += output;
        }
        conn.disconnect();         



        System.out.println("Employee name: " + em.getEmployeeName());

}   
catch (MalformedURLException e) { 
    e.printStackTrace(); } 
    catch (IOException e) { 
    e.printStackTrace();        
}
 }}

使用第二个代码,我没有收到该错误,但没有插入数据库(使用 postman 使用 GET 方法检查)...

嗯,我错过了什么?我想,我错过了一些基本的东西......

最佳答案

使用 url.openConnection 两次意味着您获得两个不同的连接。您将请求发送到第二个连接,并尝试从第一个连接读取响应。您应该在最初打开的连接上调用 doOutput。

第二个问题是您在发送请求之前调用 getResponseCode。在http中,请求必须在服务器发送响应之前完全发送。您应该将调用 doOutput 并写入请求正文的代码移到尝试检查响应代码的代码之前。

关于Java:如果 doOutput=false,则无法写入 URLConnection - 调用 setDoOutput(true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029598/

相关文章:

java - junit:使用mockmvc测试 Controller 时注入(inject)bean上的NullPointer

java - 使用 RC4 在 java 中加密字符串并在 VBScript 中解密

json - 为什么在 Swift 中尝试序列化 JSON 时会出现错误?

javascript - Ember.js/Rails 将关系发布到 Rails

c# - 读取 HttpwebResponse json 响应,C#

rest - 如何找到Cloud Firestore项目的数据库ID?

java - 合适的 Eclipse 版本吗?

c# - Xamarin : iOS won't send punctuation in strings to a web endpoint

java - Alfresco REST api 'groups/children?level="ALL"',是否存在类似的东西?

java - Trade Me API - API 访问之前的 OAuth