简体   繁体   English

Http Post的响应代码为415。如何使响应代码为200

[英]Http Post's response code is 415. How to make the response code to be 200

I made a complicated Json object in my Java program. 我在Java程序中创建了一个复杂的Json对象。 I tried to request a Http Post, but the response code is 415, I want to see the response code to be 200, because 200 means ok. 我尝试请求Http Post,但响应代码为415,我想查看响应代码为200,因为200表示可以。 Who can help me solve this problem? 谁能帮助我解决这个问题?

String post_url = "https://candidate.hubteam.com/candidateTest/v3/problem/result?userKey=1cae96d3904b260d06d0daa7387c";
URL obj = new URL(post_url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
String urlParameters = res.toString();

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);


// the following is an example about how did I build the complicated Json object
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name","Sam");
jsonObject1.put("age",7);

JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name","David");
jsonObject2.put("age",10);

List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
jsonObjects.add(jsonObject1);
jsonObjects.add(jsonObject2);
jsonObject.put("fans",jsonObjects);

I want to see the response code to be 200, instead of 415 我想看到响应代码是200,而不是415

I believe that you want to put this in your code! 我相信您想将其放入代码中! If you note define the method http in your connection it is get change to post with setRequestMethod 如果您注意到在连接中定义方法http,则将其更改为使用setRequestMethod发布

con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");

As I mentioned in the comment to the original post, HTTP status 415 is: unsupported media type. 正如我在原始帖子的评论中提到的,HTTP状态415为:不支持的媒体类型。 Set content-type header: 设置内容类型标题:

con.setRequestProperty("Content-Type", "application/json; charset=utf8");

Here is the core part for sending a POST request to the server with the body (here assumed HttpUrlConnection, change it to HttpsURLConnection if needed): 这是用于通过主体将POST请求发送到服务器的核心部分(此处假定为HttpUrlConnection,如果需要,将其更改为HttpsURLConnection):

URL url = new URL("http://localhost:90/guide/channel");
String data = createRequestData();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Not needed, default is true
//con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Content-Type", "application/json");
DataOutputStream outputStream = new DataOutputStream(con.getOutputStream());
outputStream.writeBytes(data);
outputStream.flush();
outputStream.close();

If you want to create a JSON array use JSONArray . 如果要创建JSON数组,请使用JSONArray Use the following code to create request payload: 使用以下代码创建请求有效负载:

JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name","Sam");
jsonObject1.put("age",7);

JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name","David");
jsonObject2.put("age",10);

JSONArray jsonObjects= new JSONArray();
jsonObjects.put(jsonObject1);
jsonObjects.put(jsonObject2);

JSONObject jsonObject = new JSONObject();
jsonObject.put("fans", jsonObjects);

System.out.println(jsonObject); // {"fans":[{"name":"Sam","age":7},{"name":"David","age":10}]}

Here is the full runnable code to make POST requests, read error response or expected response (change the URL, HttpURLConnection/HttpsURLConnection and createRequestData() to create your payload): 这是发出POST请求,读取错误响应或预期响应的完整可运行代码(更改URL,HttpURLConnection / HttpsURLConnection和createRequestData()以创建有效负载):

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostJsonData {
    public static void main(String[] args) throws Exception {
        new PostJsonData().postData();
    }

    private void postData() throws Exception {
        URL url = new URL("http://localhost:90/guide/channel");
        String data = createRequestData();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        // Not needed, default is true
        //con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.addRequestProperty("Content-Type", "application/json");
        DataOutputStream outputStream = new DataOutputStream(con.getOutputStream());
        outputStream.writeBytes(data);
        outputStream.flush();
        outputStream.close();
        readResponseStatusAndHeaders(con);
        if (con.getResponseCode() == 200) {
            System.out.println("Output:");
            processResponse(con.getInputStream());
        } else {
            System.out.println("Error");
            processResponse(con.getErrorStream());
        }
    }

    private String createRequestData() {
        JSONObject data = new JSONObject();
        data.put("name", "Star Movies");
        data.put("channelGroup", "Star");
        JSONObject additionalInfo = new JSONObject();
        additionalInfo.put("description", "additional info");
        data.put("additionalInfo", additionalInfo);
        return data.toString();
    }

    /**
     * Reads response code, message and header fields.
     *
     * @param connection Http URL connection instance.
     * @throws IOException If an error occrred while connecting to server.
     */
    private void readResponseStatusAndHeaders(HttpURLConnection connection) throws
            IOException {
        System.out.println("Response code: " + connection.getResponseCode());
        System.out.println(
                "Response message: " + connection.getResponseMessage());
        System.out.println("Response header: Content-Length: " + connection.
                getHeaderField("Content-Length"));
    }

    /**
     * Prints the response to console.
     *
     * @param response Response stream.
     */
    private void processResponse(InputStream response) {
        if (response == null) {
            System.out.println("No or blank response received");
        } else {
            StringBuilder data = new StringBuilder();
            try {
                int bufferSize = 2048;
                byte[] inputData = new byte[bufferSize];
                int count = 0;
                while ((count = response.read(inputData, 0, bufferSize)) != -1) {
                    data.append(new String(inputData, 0, count, "UTF-8"));
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println("Data received: " + data.toString());
        }
    }
}

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

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