Hi i have no idea about java, but for testing purpose i need some code to do http post request with json parameters in java. I have collected few examples and written the code below but its not working.
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); } File name: SimpleURL.java compilation in linux: javac SimpleURL.java Error:
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"); ^