Reputation: 1362
I've found this example code online. It seems to do what I want, making a request to an API, I just need to customize it a bit.
However, it when I try to compile it, it gives me the same errors for three lines
Syntax error on token(s), misplaced
construct(s)
- Syntax error on token "setEntity", =
expected after this token
Maybe some one can see something I don't?
Here's the code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class http {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
}
The error is thrown for the nameValuePairs.add lines, and the httppost.setEntity line
Upvotes: 0
Views: 66
Reputation: 5410
In addition to what Ran said: you may want to pick up some basic Java programming lessons / tutorials first. Some programming-related tutorials assume that you are already familiar with that and just list a few lines of code that are not directly usable that way, because they belong inside a method.
You need to rewrite your class as follows ("myMethodName" can be any other name of your choice)
public class http {
public void myMethodName() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
}
}
And then this piece of code cannot be executed as is. You need to create an instance of your class "http" and call its "myMethodName" method from an Android Activity.
Upvotes: 2