带有json post参数的java中简单的http post请求

时间:2014-03-31 12:43:31

标签: java http post

您好我不知道java,但出于测试目的,我需要一些代码来用java中的json参数执行http post请求。我收集了一些示例并编写了下面的代码,但它不起作用。

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import com.google.gson.Gson;

public class pojo1
{
 String name=abc;
 String age=18;
 //generate setter and getters
}

 public class SimpleURL
{
 String postUrl="www.site.com";// put in your url
 Gson gson= new Gson();
 HttpPost post = new HttpPost(postUrl);
 StringEntity  postingString =new StringEntity(gson.toJson(pojo1)); //convert to json
 post.setEntity(postingString);
 post.setHeader("Content-type","application/json");
 HttpResponse  response = httpClient.execute(post);
} 

文件名:SimpleURL.java 在linux中编译:javac SimpleURL.java 错误:

SimpleURL.java:22: <identifier> expected
post.setEntity(postingString);
          ^
SimpleURL.java:22: <identifier> expected
post.setEntity(postingString);
                        ^
SimpleURL.java:23: <identifier> expected
post.setHeader("Content-type","application/json");
          ^
SimpleURL.java:23: illegal start of type
post.setHeader("Content-type","application/json");
           ^
SimpleURL.java:23: illegal start of type
post.setHeader("Content-type","application/json");
                          ^

2 个答案:

答案 0 :(得分:1)

您的代码无法编译。为了编译,您只需要将SimpleURL中的代码放在main方法中,如下所示:

public class SimpleURL{
    public static void main(String[] args) {
        String postUrl="www.site.com";// put in your url
        Gson gson= new Gson();
        HttpPost post = new HttpPost(postUrl);
        StringEntity  postingString =new StringEntity(gson.toJson(pojo1)); //convert to json
        post.setEntity(postingString);
        post.setHeader("Content-type","application/json");
        HttpResponse  response = httpClient.execute(post);
    }
}

您还需要将www.site.com更改为目标网站。 不应将pojo1声明为public。您可以将它保存在同一个文件中。

答案 1 :(得分:0)

您的代码无法编译,可能是因为您已在同一文件中定义了2个公共类。

public class pojo1
public class SimpleURL
相关问题