【问题标题】:HTTP Post from Postman working but not through browser来自 Postman 的 HTTP Post 工作但不通过浏览器
【发布时间】:2017-09-22 06:45:43
【问题描述】:

我将 JaxRS jersey 用于服务器,并且已将其部署在 aws 上。对服务器的 Http 发布请求正在使用邮递员,但不适用于 Http post apache 客户端。 以下是我的 Java for Rest 服务

@Path("/data")
public class MyResource {


    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<trackerdetails> getIt() {
        SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionfactory.openSession();
        session.beginTransaction(); 
        trackerdetails user = new trackerdetails();
        List<trackerdetails> sendlist = (List<trackerdetails>) session.createQuery("from trackerdetails").list();

        session.getTransaction().commit();
        session.close();
        return sendlist;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public trackerdetails putit(trackerdetails track) {
        track.setDate(new Date());
        SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionfactory.openSession();
        session.beginTransaction(); 

        session.save(track);
        session.getTransaction().commit();
        session.close();
        return track;
    }

以下是我的 trackerdetails 类

@Entity
@XmlRootElement
public class trackerdetails {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private int autoid;
    private String latitude;
    private String longitude;
    private String devicename;
    private Date date;
    public trackerdetails(){

    }
    public int getAutoid() {
        return autoid;
    }
    public void setAutoid(int autoid) {
        this.autoid = autoid;
    }
    public String getLatitude() {
        return latitude;
    }
    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }
    public String getLongitude() {
        return longitude;
    }
    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }
    public String getDevicename() {
        return devicename;
    }
    public void setDevicename(String devicename) {
        this.devicename = devicename;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

以下是我的客户端 http post 请求

HttpPost httpPost = new HttpPost("myurl");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("devicename", "vip"));
nvps.add(new BasicNameValuePair("date", "hjksvn"));
nvps.add(new BasicNameValuePair("latitude", "hello"));
nvps.add(new BasicNameValuePair("longitude","hi"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));


httpPost.setHeader("Cache-Control", "no-cache");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Host", "trackertest.herokuapp.com");


CloseableHttpResponse response2 = httpclient.execute(httpPost);

try {
    System.out.println(response2.getStatusLine());
    System.out.println(response2.toString());
    HttpEntity entity2 = response2.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
      BufferedReader rd = new BufferedReader(
    new InputStreamReader(response2.getEntity().getContent()));

StringBuffer result1 = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
    result1.append(line);

        System.out.println(line);
        System.out.println("");
}
System.out.println(result1);
    EntityUtils.consume(entity2);
} finally {
    response2.close();
}

以下是我的错误状态是 400 错误的请求

说明客户端发送的请求语法错误。

【问题讨论】:

  • HttpPost httpPost = new HttpPost("myurl"); 看起来不一样,请将其更改为 HttpPost httpPost = new HttpPost(myurl);
  • 网址是正确的 我的意思是我已经添加了网址

标签: javascript java eclipse jersey jax-rs


【解决方案1】:

您的 REST API 需要 JSON 格式的请求,但您使用 NameValuePair 构造请求正文的方式不会导致 JSON 格式。

您应该使用一些可以将对象转换为JSON(如Jackson)的库来生成有效的JSON 请求正文,或者您可以手动构造JSON 请求正文,然后调用您的API。

下面是手动构造JSON请求体的一种方式-

HttpPost httpPost = new HttpPost("myurl");

StringBuilder jsonBody = new StringBuilder();
jsonBody.append("{");
jsonBody.append("\"devicename\" : ").append("\"vip\"").append(",");
// Pass a valid date because on server side, you are using Date object for accepting it
jsonBody.append("\"date\" : ").append("\"2017-09-23\"").append(",");
jsonBody.append("\"latitude\" : ").append("\"vip\"").append(",");
jsonBody.append("\"longitude\" : ").append("\"vip\"");
jsonBody.append("}");

StringRequestEntity requestEntity = new StringRequestEntity(jsonBody.toString(),"application/json","UTF-8");


httpPost.setRequestEntity(requestEntity);

httpPost.setHeader("Cache-Control", "no-cache");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Host", "trackertest.herokuapp.com");
// Rest code should remain same

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2019-07-16
    • 2020-07-10
    • 2013-07-21
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多