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

时间:2019-08-17 22:21:37

标签: java json http-post

我在Java程序中创建了一个复杂的Json对象。我尝试请求Http Post,但响应代码为415,我想查看响应代码为200,因为200表示可以。谁可以帮助我解决这个问题?

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

我希望看到的响应代码是200,而不是415

2 个答案:

答案 0 :(得分:0)

我相信您想将其放入代码中! 如果您注意到在连接中定义方法http,则可以更改为使用setRequestMethod

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

答案 1 :(得分:0)

正如我在原始帖子的评论中提到的,HTTP状态415为:不支持的媒体类型。设置内容类型标题:

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

这是用于向主体发送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();

如果要创建JSON数组,请使用JSONArray。使用以下代码创建请求有效负载:

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}]}

以下是完整的可运行代码,用于发出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());
        }
    }
}