在Java for REST API中使用HttpURLConnection进行POST时,响应代码为400

时间:2016-05-25 22:23:49

标签: java json rest httpurlconnection

我是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);
		
		
	}
	
}

1 个答案:

答案 0 :(得分:1)

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