This is roughly the code I'm working with now:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", json.toString()));
nameValuePairs.add(new BasicNameValuePair("blob", file.getAbsolutePath()));
post_request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
The the reply I get back from the server is good for the first add() statement but, for the second one I'm not trying to send the path, I'm trying to send the file. Taking off .getAbsolutePath() should do the trick, but It won't let me as it only accepts strings. How would I go about sending the file?
you should use a MultipartEntity, not an UrlEncodedForm one. In a Multipart body you can store objects of different mime types
Related
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
I'm working on Telegram api in my java application. I need to do authentication and authorization with my telegram account and get message list of my specific group. For this purpose, first I got api_id, api_hash and MTProto servers from telegram site. Second, I tried to authorize my account with auth.sendCode method in this way:
...
String url = "https://149.154.167.40:443/auth.sendCode";
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.addHeader("charset", "UTF-8");
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("phone_number", myPhoneNumber));
nameValuePairs.add(new BasicNameValuePair("sms_type", "5"));
nameValuePairs.add(new BasicNameValuePair("api_id", api_id));
nameValuePairs.add(new BasicNameValuePair("api_hash", api_hash));
nameValuePairs.add(new BasicNameValuePair("lang_code", "en"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
...
But this returns me javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake exception. I tested url with http instead of https and this returned 404 Not Found html content. What is the correct way for calling telegram api method in java?
Update:
I tried using java socket for sending TCP post request, but this returns me 404 not found.
Since it's mproto protocol, you must obey their specification - https://core.telegram.org/mtproto
I suggest you to use this project, since it has working examples - https://github.com/badoualy/kotlogram
I have a webservice which receives 2 (optional) parameters:
<resource path="getLogbookEvents">
<method name="POST">
<request>
<param name="startDate" style="query" type="xs:string"/>
<param name="endDate" style="query" type="xs:string"/>
</request>
<response>
<representation mediaType="application/json"/>
</response>
</method>
</resource>
I'm able to connect and receive an answer from Android using HttpPost, but the web service never receives either of the two parameters.
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://... method URL ...");
//post.setHeader("media-type", "application/json; charset=UTF-8");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("startDate", "2014-04-18T05:00:00"));
nameValuePairs.add(new BasicNameValuePair("endDate", "2014-04-18T06:00:00"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
// entity.setContentEncoding(HTTP.UTF_8);
post.setEntity(entity);
// make POST request to the given URL
HttpResponse httpResponse = httpclient.execute(post);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
I have tried HttpParams, JSONObject and nameValuePairs and nothing works. I just keep receiving the response as if I didn't specify any parameters. Any ideas on why this could be happening or other things I could try to get the winning combination?
not a direct answer, never used httpclient directly but to debug/fix this issue you could:
use proxy and see what data is really being sent from your phone
use easy to use http libs such as http-request
or retrofit
go for http-request. it is dead simple to use. trust me.
I finally managed to get it working.
So, first of all, there's definitely something wrong with the webservice.
I'm not exactly sure what, and it's not my business to fix it, so I'm not even going to try to pinpoint what it was.
Basically, the getLogbookEvents wasn't receiving parameters because it won't accept any parameters inside the body of the request, period. Looking at the SoapUI raw data being sent I discovered that it was always sending the parameters inside the URL, not the body ...
I have no idea how they got a POST method to behave like a GET method, but as it stands they apparently do. Formatting my nameValuePairs in UTF-8 and adding them to the URL is the (totally backwards and not recommended at all) way I got it to work :)
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("startDate", "2014-04-18T05:00:00"));
nameValuePairs.add(new BasicNameValuePair("endDate", "2014-04-18T06:00:00"));
String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
HttpPost post = new HttpPost("... basic URL String ..." + paramString);
I have been trying to understand the postData() method in the following tutorial.
My understanding of the code is:
an nameValuePairs object, which contains some data is being sent over the internet to some web service located at this address: http://www.yoursite.com/script.php which will receive this nameValuePairs object
For example you want to send the age of a person to the webservice.
If you send data via GET the call of the webservice would be like this:
http://www.yoursite.com/script.php?age=18
If you send data via POST the call of the webservice would be like this:
http://www.yoursite.com/script.php
and the key-value arguments are integrated in the data stream of the request
So, to answer your question, no object will be sent,
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("age", "18"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
will integrate the key-value-list to the data stream of the request.
Yes, basically... server gets that name-value pair and can process it as it wants ...
For example when logging into your email account, you are sending two name-value pairs - username=your_username and password=your_password ... after receiving, server checks if username you sent is correct and if the password is valid for given username, and then sends you to your account or throws a message that data you supplied is invalid.
It is not java specific. It is http protocol, that can be implemented in any other language.
If you pass an id in like this,
nameValuePairs.add(new BasicNameValuePair("id", "20"));
In php page, you can get the value like this,
$id= $_POST['id'];
i m trying to send post request to webservice..
when i add special character # in parameter it is coverted to %40.i have checked server side..they are getting %40 instead of #.
can any one help me??
here is my code..
httpclient = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Email", "abc#gmail.com"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost,responseHandler);
i have also tried this method to prevent my parameter from encoding.
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.PLAIN_TEXT_TYPE));
but it raised unsupported encoded algorithm
pls help me out of this.
You're using UrlEncodedFormEntity, which will URL-encode the content. Turning # into %40 is normal with this encoding. The recipient should be able to decode that automatically, although you may have to use the correct content type for it to do so, probably application/x-www-form-urlencoded.
You can use
URLDecoder.decode("urlcontext", "UTF-8");
to remove any special character from the url which your passing
You need to use something such as URLDecoder on your server side so that you can convert the %40 back to #. The same applies for other special characters.
Use URLDecoder.decode(url) this will be helpful.
I'm definitly late for this party, but I had a similar issue. If you want to decode your url string you need to use decodeURIComponent(url). Where url is the string you are trying to decode.
W3schools does a great job of explaining it. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_decodeuricomponent