Reputation: 139
I need to fill basic Google Form from my Java code but it throws org.apache.http.client.ClientProtocolException: Unexpected response status: 405
Here is my code :
private boolean sendMessage(UserInfo userInfo) {
final HttpPost req = new HttpPost("my-form-url");
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("entry.1301726507", userInfo.getName()));
form.add(new BasicNameValuePair("entry.1466759457", "hello"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);
req.setEntity(entity);
System.out.println("Executing request " + req.getRequestLine());
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity responseEntity = response.getEntity();
return responseEntity != null ? EntityUtils.toString(responseEntity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(req, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
And here is the form :
what am I doing wrong?
Upvotes: 1
Views: 1156
Reputation: 905
You may use my pet project to do the job for you:
Add dependency:
<dependency>
<groupId>io.github.stepio.jgforms</groupId>
<artifactId>jgforms</artifactId>
<version>1.0.1</version>
</dependency>
Define your form:
public enum MyForm implements MetaData {
USER_NAME(1301726507L),
MESSAGE(1466759457L);
private long id;
JGForm(long id) {
this.id = id;
}
@Override
public long getId() {
return this.id;
}
}
Fill the form and submit:
private boolean sendMessage(UserInfo userInfo) {
URL url = Builder.formKey("my-form-key-from-url")
.put(MyForm.USER_NAME, userInfo.getName())
.put(MyForm.MESSAGE, "hello")
.toUrl();
Submitter submitter = new Submitter(
new Configuration()
);
try {
submitter.submitForm(url);
} catch (NotSubmittedException ex) {
// TODO: log & handle the exception properly
return false;
}
return true;
}
Check README and unit tests for more details and examples:
https://github.com/stepio/jgforms
Upvotes: 2