嗨,我对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 中的代码放入 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
。不过,您可以将其保存在同一个文件中。
关于java - java中的简单http post请求,带有json post参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22761852/