创建实体的网址是什么?通过其他网址说myEntity
? myEntity
有两个参数name
和description
。
以下是休息控制器的样子:
@POST
@Path("/create")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createJobType(MyEntity myEntity) {}
如果它看起来不错,那么myEntity
参数将如何通过请求网址传递?
这是测试类:
@Test
public void testShouldCreateMyEntity() {
MyEntity entity = new MyEntity();
entity.setName("Sample Name");
entity.setDescription("Sample Description);
String url = buildRequestURL("/create/"+entity).toUrl(); // Confused :(
}
不确定我是否应该通过URL传递实体。如果没有那么实体将如何通过?
答案 0 :(得分:0)
有许多方法可以测试您的终端,这些测试可能会根据您的需求而有所不同。
例如,如果需要身份验证,或者需要HTTPS。
但假设您不需要身份验证且未使用HTTPS,则可以使用以下代码测试您的终端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import com.google.gson.Gson;
public class RestClientTest {
/**
* @param args
*/
public static void main(String[] args) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("http://localaddressportetc.../create"); // <-- I suggest you change this to "entity" since this is what is being created by the POST
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/json"));
MyEntity entity = new MyEntity();
entity.setName("Sample Name");
entity.setDescription("Sample Description");
Gson gson = new Gson();
String entityJSON = gson.toJson(entity);
StringEntity input = new StringEntity(entityJSON);
input.setContentType("application/json");
httpPost.setEntity(input);
for (NameValuePair h : nvps)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}