我是 REST API 的新手。我需要发布到网站,但我得到的响应代码为 400,内容类型为 text/plain
如果我使用谷歌的高级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 Client :
这里是一个例子:
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));
关于java - 在 REST API 的 java 中使用 HttpURLConnection 进行 POST 时,响应代码为 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37448644/