Java posting to http fields/form keeps failing - java

Ok so I have tried a lot of stuff including sockets,httpConnection,httpClients,proxies,using cookies,and wide array of other things but this just keeps failing.What I need my program to do is send some data to html site and then recive adquate response.But resposne is always exact opposite of what I am expection.To be little more specific site I am talking about is http://hidemyass.com and I need to set the field value to "http://reddit.com" whos name is u and then press the button witch will redirect to Reddit through a proxy.So in theory response I should get is the Reddit html source or regular server response.But what I keep getting is http://hidemyass.com html source code with default values set(aka as I have not sent those values over a connection to it).
So here is what I did and it did not work.
CODE:
//I will skip used import because I think they are not of importance
//Also try catch blocks will be skipped and not written
private static UrlEncodedFormEntity entity;
public static void main(String[] args){
HttpClient client=new DefaultHttpClient();
ArrayList<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("u","http://reddit.com");
params.add(new BasicNameValuePair("hmabutton,"Hide My Ass");
entity=new UrlEncodedFormEntity(params,null)//there is no encoding on this site
HttpPost post=new HttpPost("http://hidemyass.com");
post.setEntity(entity);
HttpResponse response=client.execute(post);
HttpEntity ent=response.getEntity();
System.out.println(EntityUtils.toString(ent));
}
Can anyone help me see my error finally and get the site to do what I want?

You must post your request to the form's action URL:
HttpPost post=new HttpPost("http://hidemyass.com/process.php");

Related

How to make Java HttpPost NOT include url in body

We have some old java code that POSTs some fields and values to a dotnet5 web api - The api is having problems dealing with the body of the POST as it includes the url/uri as the first part of the body.
The Java sends: http://127.0.0.1:5555?producerRef=GREEN&systemId=78&status=false
But the api is expecting something like: producerRef=GREEN&systemId=78&status=false
as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example. If we send a test message via Postman then the api has no problems.
This is the Java code:
List<NameValuePair> params = new ArrayList<NameValuePair>(queryParams.size());
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// the address is just that, there's NO parameters
HttpPost post = new HttpPost(this.cmAddress.toURI());
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
It's quite simple, but always adds the url to the start of the body of the request. If this is the only way to produce this, what could I do to produce something that looks like this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example
Many Thanks.
This request seems like a GET request rather than a POST since the request params are in the URL. i don't know about the specifications of the Api you're using, but you can try OKHTTP, you can easily copy the code directly from postman
Postman Get example:
Your issue seems to be at below line
HttpPost post = new HttpPost(this.cmAddress.toURI());
This is the only place which will set the POST url ( another way is to use setURI which is not called anywhere in the code sample you have shared).
If you can use a debugger try checking the value of cmAdress variable

Send xml as part of URL request in Java

This might be a trivial question but I'm trying to send web request to USPS to get a http post response (or email response depending on my request) containing the tracking information based on the tracking number that I send in. The documentation says the xml needs to appended as part of the url like below
http://secure.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<PTSEmailRequest USERID="xxxxx"><TrackId>xxxxx</TrackId><RequestType>EN</RequestType></PTSEmailRequest>
I saw there were 2 ways to make an xml request, one using HttpPost and the other URLConnection. I'm a bit thrown by how I go about this and I'm failing to appreciate what's the difference between appending xml in the url and a normal http request. Can someone please clear things up for me?
USPS documentation for tracking =>
https://www.usps.com/business/web-tools-apis/track-and-confirm.pdf
I read these related Stackoverflow posts
Java: How to send a XML request?
posting XML request in java
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://secure.shippingapis.com/ShippingAPITest.dll");
List<String> params = new ArrayList<String>(2);
params.add(new BasicNameValuePair("API", "TrackV2"));
params.add(new BasicNameValuePair("XML", FuncTOGenerateXML()));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
//.....
// .....
instream.close();
}
An HTTP request can use one of several methods, like POST, GET, DELETE, PUT... Here we talk about POST and GET
Technical differences
With GET, the data is retrieved from the parameters in the URL.
With POST, the data is retrieved from the data transmitted inside the HTTP message.
Intended use differences
GET is intended to be used when the request does not cause a change (v.g., searching in Google). Since you can repeat the request without side effects, the data is in the URL and can be stored in the browser history, favorites, etc.
POST is intended to use when you are performing a change (v.g. sending an e-mail, doing a on-line purchase). The data related is not stored with the URL (it is then that, if you go back to a page that was obtained using POST, the browser many times will show you a pop-up asking for permission to send the data again.
In real usage, the distinction is not so clear cut, in particular POST is sometimes used when the data is too large (URLs have limited length). Also, sometimes GET is used with the meaning of POST so the data can be presented as an HTML link.
Finally, URLConnection is the basic API for opening a connection (which you can use as a POST or GET request, based in how you pass the data, or something else) and HttpPost is just a higher level API for creating a POST request. If you go the basic way, use HttpURLConnection better.

Box API Updating Email Alias Issue

I am trying to update email alias for different users. I am able to authenticate, get the code and then get the access token. I am sending the access token in the HTTP POST request as a Header. I am using Java & Apache HTTPClient to make the RESTful call. Here is the code snippet (Only relevant code shown).
if (httpClient != null) {
String apiURL = getApiURL();
apiURL = MessageFormat.format(apiURL, "firstname.lastname#company.com");
// apiURL = https://api.box.com/2.0/users/firstname.lastname#company.com/email_aliases
// firstname.lastname#company.com does exist in the Box Account
HttpPost post = new HttpPost(apiURL);
post.addHeader("Authorization", "Bearer "+accessToken);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", "updateemail#company.com"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.defaultCharset()));
HttpEntity entity = post.getEntity();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseFromBox = httpClient.execute(post, responseHandler);
writeResponse(response, responseFromBox);
if (responseFromBox != null) {
if (logger.isDebugEnabled()) {
logger.debug("apiURL-->"+apiURL);
logger.debug(responseFromBox);
}
}
}
The problem is that the response I get is some HTML code that says "The page you were viewing has expired. Please go back and try your request again." I was expecting some JSON string.
What I am doing incorrect? In the Post request instead of sending the email address I used the user id. But I get the same error.
In fact when I try to fetch the email alias of a user using the HTTP GET request I get an error "Not Found". The user does exist. I have an admin control. I can see them.
Thanks
Raj
Try a get on /users to get the array of all your users in the enterprise first. Is that working for you? If not, can you do a get on /users/me? If you can't get the former, then your API key may not have the "manage an enterprise" grant setup for it. You have to set that up in the app management, where you setup your OAuth2 callback URL.
Not sure why you are getting HTML back. That usually only happens on badly formed requests that our servers can't even parse, like you are hitting the wrong URL.
Just a reminder, OAuth2 URL is different from the API URL. 1st is https://www.box.com/api/oauth2/.... 2nd is https://api.box.com/2.0/...
As for setting the Email alias, that's entirely possible, once you know the ID of the user you are trying to set the alias for. Documentation is here
I was using the NameValuePair instead of the JSON string that was being expected. So I removed the following
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", "updateemail#company.com"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.defaultCharset()));
and added
String json = "{\"email\":\"firstname.lastname#company.com\"}";
StringEntity entity = new StringEntity(json, Charset.defaultCharset());
post.setEntity(entity);
and then things started to work!

Does anyone have an updated example on posting a JSON request?

I am having a mess of a time finding up to date information on sending a JSON request to a local server. I keep coming across examples that use deprecated code, and I'd really like to do this with code that isn't.
I can at least say that I now have a working example, and I am not receiving any deprecated messages from NetBeans, but I would like to know if what I've put together is the right way:
public void sendUpdateRequest() {
String updateString =
"{\"jsonrpc\": \"2.0\", \"method\": \"VideoLibrary.Scan\"}" ;
StringEntity entity = new StringEntity(updateString, Consts.UTF_8);
HttpPost httpPost = new HttpPost(getURL()); // http://xbmc:xbmc#10.0.0.151:8080/jsonrpc
entity.setContentType("application/json");
httpPost.setEntity(entity);
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine()); // move to log
}
catch (IOException e) {
e.printStackTrace(); // move to log
}
}
This is something I'm working on to update XBMC with a JSON HTTP request
Edit
Changed the code to try with resources per the comment -- hopefully this will be useful for someone else dealing with JSON and Java
but I would like to know if what I've put together is the right way:
Yes, you are doing it correctly given the details you've posted.
The StringEntity contains the body of the request. You can set any appropriate headers there. Any other headers can be set directly on the HttpPost object.
As stated in the comments, don't take any chances, close() the CloseableHttpClient in a finally block.

Using HTTP Post on an android device to put data on google app engine's blob store

I am trying to post data to the Blob Store on google's app engine, this code runs without throwing any exceptions, but on the blobstore end there is no log on the post request at all. The server side stuff works when i post using a form (albeit with mime data). I have allowed my android app to use internet. This is a stab in the dark but if any of you folks might have had an issue like this before perhaps the problem i am having might ring a bell!
public void sendVideo() throws IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.theurliampostingto.com/au813rsadjfaruh);
// Add your data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
pairs.add(new BasicNameValuePair("key2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
}
You can try to intercept the traffic between the emulator and the server i.e. with WireShark to see if the server is responding to your request at all.
Your code looks good for me.

Categories

Resources