Below is a snipped from a Java Client that connects to a website and uploads a file via the POST method. I have to reproduce this client in a Visual Studio environment, but I don't see any equivalent functions in the .NET environment for the setEntity() function used in the Java.
Everything I've found points to using this...
public void uploadFile(File uploadFile, String partner, String key,
String baseUrl,boolean isPartner) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1
);
String url = baseUrl + "?" + (isPartner ? "partnerId" : "ori") + "="
+ partner.toUpperCase() + "&authKey="
+ key+ "&key="
+ key;
HttpPost httppost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(uploadFile, "text/xml");
multipartEntity.addPart("dataFile", contentBody);
httppost.setEntity(multipartEntity);
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Everything I've found in Visual studio uses something like this below for the POST method. The WebRequest object has no obvious way of adding the parameters I need.
Dim request As WebRequest = WebRequest.Create("http://Test.com/import?partnerId=2&authKey=XdUa")
request.Method = "POST"
Dim postData As String = StrData
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "dataStr"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Any guidance would be greatly appreciated. If my question is not clear, let me know, I'll try again.
You can add following code snippet to add the parameter
request.ContentType="application/x-www-form-urlencoded"
Dim postData As String = "name1="+value1+"&name2="+value2
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Rest will remain same.
Related
I have a requirement to call a controller from java code itself. The controller is as follows,
#RequestMapping(value = "temp", method = RequestMethod.POST)
#ResponseBody
public String uploadDataFromExcel(#RequestBody Map<String, String> colMapObj, #ModelAttribute ReqParam reqParam) {
}
I am trying to call the above controller using http post as follows,
String url ="http://localhost:8081/LeadM" + "/temp/?searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
InputStream rstream = entity.getContent();
jsonObject = new JSONObject(new JSONTokener(rstream));
where reqParam is a class object is the class object and colMapObj is the map that I want to pass to the above controller. However when http post is executed it gives exception in the url.
If anybody knows the right way then please suggest, thank you.
This should work
#RequestMapping(value = "/temp", method = RequestMethod.POST)
#ResponseBody
public String uploadDataFromExcel(#RequestBody Map<String, String> colMapObj, #ModelAttribute ReqParam reqParam) {
}
and url should be
String url ="http://localhost:8081/LeadM" + "/temp?"+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
URL dos not work with spaces.From your code above: " &exportDiscardRec="
To avoid such issues use URIBuilder or something similar if possible.
Now for the request, you are not building your request correctly for example you do not provide the body.
Check below example:
Map<String, String> colMapObj = new HashMap<>();
colMapObj.put("testKey", "testdata");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
JSONObject body = new JSONObject(colMapObj);
StringEntity entity = new StringEntity(body.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getEntity().toString());
client.close();
More examples just google "apache http client post examples" (e.g. http://www.baeldung.com/httpclient-post-http-request)
Encode your query string.
String endpoint = "http://localhost:8081/LeadM/tmp?";
String query = "searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
String q = URLEncoder.encode(query, "UTF-8");
String finalUrl = endpoint + q;
If this doesn't work, then encode individual params before concatenating.
On a side note
if you r running in same jvm then you can call method directly
if you own the the upload method then consider changing query string into form param
I am trying to post xml data to API using HTTP post method with credentials but a getting HTTP/1.1 400 Bad Request error .. Can anyone pl help me out ....
Here is my sample code:
BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);
params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());
StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}
First of all, your form parameters are not encoded correctly. You are using colon (:) to separate keys from their values, but instead, the equal sign (=) must be used:
Wrong: "importFormatCode:1&data:" + params
Correct: "importFormatCode=1&data=" + params
(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded)
Apart from that, you must not URL-encode the entire string but only the keys and the values. Otherwise you'll also encode the separator characters = and &!
The easiest way is to use the existing utility class org.apache.http.client.utils.URLEncodedUtils (assuming that you're using Apache HTTP Components):
String xmlData = // your xml data from somewhere
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request
StringEntity entity = new StringEntity(body);
// rest of your code
I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity for your PostMethod:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity for binary data are ByteArrayRequestEntity for byte[], FileRequestEntity which reads the data from a file (since 3.1) and InputStreamRequestEntity, which can read from any input stream.
Before 3.0 you can directly set a String or an InputStream, e.g. a ByteArrayInputStream, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity implementations: ByteArrayEntity, InputStreamEntity, FileEntity, ...
i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name
my code
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
Answer
I'm working on simple client server communication using HttpPost. From the client side I'm setting a parameter(filename).
At the server side when I try to get the parameter value it's always showing null. I tried using MultiPartEntity but even that is not working.
Below is my client code:
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx:yyyy");
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(dataFile), -1);
reqEntity.setContentType("binary/octet-stream");
// Send in multiple parts if needed
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
//setting the parameter
httppost.getParams().setParameter("filename", "xxxx.xml");
HttpResponse response = httpclient.execute(httppost);
int respcode = response.getStatusLine().getStatusCode();
And this is my servlet code:
response.setContentType("binary/octet-stream");
Scanner scanner = new Scanner(request.getInputStream());
// reading the parameter
String filename = request.getParameter("filename");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\" + filename)));
Kindly let me know any possible solution for this issue.
Thanks in advance!
Ur setting parameters wrong... at the client side, do this:
ArrayList<NameValuePair> postParameters = postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("filename", "xxxx.xml");
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
I need to encode the params to ISOLatin which i intend to post to the site. I'm using org.apache.http. libraries. My code looks like follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("www.foobar.bar");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpParams params = new BasicHttpParams();
params.setParameter("action", "find");
params.setParameter("what", "somebody");
post.setParams(params);
HttpResponse response2 = httpClient.execute(post);
Thank you!
You are setting parameters wrong. Here is an example,
PostMethod method = new PostMethod(url);
method.addParameters("action", "find");
method.addParameters("what", "somebody");
int status = httpClient.executeMethod(method);
byte[] bytes = method.getResponseBody();
response = new String(bytes, "iso-8859-1");
if (status != HttpStatus.SC_OK)
throw new IOException("Status code: " + status + " Message: "
+ response);
The default encoding will be Latin-1.