嗨,我对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");
                          ^

最佳答案

您的代码无法编译。为了进行编译,您只需要将来自SimpleURL的代码放入以下主要方法中:

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。您可以将其保存在同一文件中。

10-08 18:22