2014-03-31 129 views
0

您好我不知道java,但为了测试目的,我需要一些代码来执行http发布请求与java中的json参数。我收集了几个例子,并编写了下面的代码,但它不起作用。简单的http发布请求在java与json发布参数

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"); 
         ^
+0

解释更多你想要做 – Divya

回答

1

您的代码不编译。为了编译,你只需要把从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。尽管如此,你可以将它保留在同一个文件中。

0

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

public class pojo1 
public class SimpleURL 
+0

我已经做了必要的修改,还是我的错误,http://pastebin.com/pmEggF94 –

+0

你应该有一个两个Java文件,在文件中声明YOUT pojo1类什么命名为pojo1.java,另一个用于名为SimpleURL.java的文件中的SimpleURL – gjambet