簡體   English   中英

在REST API中使用HttpURLConnection到Java中的POST時,響應代碼為400

[英]Response code is 400 while using HttpURLConnection to POST in java for REST API

我是REST API的新手。 我需要發布到網站,但是我得到的響應碼為400,內容類型為text / plain

如果我使用Google的高級REST客戶端應用程序,則會得到不同的結果。 響應碼為500,內容類型為text / html。

我沒有正確結束帖子數據(query1)嗎? 這是正確的做法嗎? 我需要使用JAX-RS嗎? 有人可以幫忙嗎? 欣賞它。

 import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import org.testng.annotations.Test; public class RestfullAPIHttpURLConnection { @Test public static void postS() throws Exception { URL url; HttpURLConnection connection = null; String urlParameters = "email=tester0@xxx.com&profileName=Tester0&password=test&roleId=1"; String email = "tester0@xxx.com"; String profileName = "Tester0"; String password = "test"; int roleId = 1; String query = String.format("email=%s&profileName=%s&password=%s&roleId=%s", (email), URLEncoder.encode(profileName), URLEncoder.encode(password), (roleId)); String query1="?"; query1 = query1.concat(query); System.out.println("query1: " +query1); String type = "application/json"; url = new URL("http://......com"); connection = (HttpURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty( "Content-Type", type ); connection.setRequestProperty( "charset", "utf-8"); connection.setUseCaches( false ); // creates an output stream on the connection and opens an OutputStreamWriter on it: OutputStream output = connection.getOutputStream(); Writer writer = new OutputStreamWriter(output, "UTF-8"); // client's output is the server's input. writer.write(URLEncoder.encode(query1, "UTF-8")); String contentType=connection.getContentType(); int responseCode=connection.getResponseCode(); int len = connection.getContentLength(); String rmsg = connection.getResponseMessage(); System.out.println("ContentType: " +contentType); System.out.println("ResponseCode: " +responseCode); System.out.println("Content length: " +len); System.out.println("URL " + connection.getURL()); System.out.println("Response msg: " + rmsg); } } 

使用Jersey客戶

這里是一個例子:

final WebTarget target = ClientBuilder.newClient().target("http://......com");

final WebTarget webTargetWithParams = target.queryParam("email", "tester0@xxx.com")
                                            .queryParam("profileName", "Tester0")
                                            .queryParam("password", "test")
                                            .queryParam("roleId", "1");

final Response response = webTargetWithParams.request().get();

System.out.println(response.readEntity(String.class));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM