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
Related
I am calling VSTS API to upload file attachment with file name having special characters. But the file name is getting truncated and all characters starting from first special characters gets truncated.e.g.if filename is file2367##$$$##
then corresponding uploaded file is file2367# and rest all characters are truncated.
Below is the code I am using for uploading attachments.
public String uploadAttachment(InputStream inputStream, String fileName) throws Exception {
fileName=URLEncoder.encode(fileName,"UTF-8");
logger.info("******file name is******* :" + fileName);
String query = getBaseUrl() + "_apis/wit/attachments?filename=" + fileName;
HttpPost httpPost = new HttpPost(query);
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json;api-version=1.0");
httpPost.setEntity(new InputStreamEntity(inputStream));
String authHeader = getAuthHeader();
httpPost.addHeader("Authorization", authHeader);
httpPost = ProxyConnectionUtility.getInstance().configureProxy(httpPost);
CloseableHttpResponse response = httpClient.execute(httpPost);
logger.info("VSTS attachment response:" + response);
HttpEntity responseEntity = response.getEntity();
String strResponse = EntityUtils.toString(responseEntity, "UTF-8");
int iStatusCode = response.getStatusLine().getStatusCode();
if (iStatusCode != 200 && iStatusCode != 201) {
throw new Exception("Record could not be updated due to the error: " + strResponse);
}
return strResponse;
}
I'm trying to invoke a REST Service which accepts a json with the two parameters param1 and param2, as below:
[{
"param1": "xxx",
"param2": "xxx"
}]
Following my code invoking MY_SERVICE_URL:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(MY_SERVICE_URL);
String json = new String("[{\"param1\": \"" + "param1Value" + "\",\"param2\": \"" + "param2Value" + "\"}]");
request.setEntity(new StringEntity(json));
request.setHeader("Content-Type", "application/json");
request.setHeader("Accept", "application/json");
try {
HttpResponse response = client.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String output = rd.readLine();
System.out.println("Response code: " + responseCode);
System.out.println("Output: " + output);
} catch(Exception ex) {
System.out.println("Error");
}
client.getConnectionManager().shutdown();
The POST is failing because it's not recognizing the first parameter as valid: instead of reading param1 it's considering the parameter \"param1\"
Any help is appreciated
Thanks
Simone
Use the below snippet to create JSON for posting over your webservice/api. Hope it helps
Add the following reference too import org.json.simple.JSONObject;
JSONObject item = new JSONObject();
item.put("param1", "testValue1");
item.put("param2", 123);
item.put("param3", "testValue3");
String json = item.toString();
Whatever I try, twilio is not accepting my JSON request for making a call. I keep getting "No 'To' number is specified". I am sending this from Java. And we intentionally didn't want to use Twilio Rest library.
JSON Response:
{"code":21201, "message":"No 'To' number is specified", "more_info":"https://www.twilio.com/docs/errors/21201", "status":400}
JSON Request object
{"Url":"http://twimlets.com/echo?Twiml=%3CResponse%3E%3CSay+voice%3D%22alice%22+language%3D%22en-IN%22%3EImportant+alert%3APlease+check+your+SMS%3C%2FSay%3E%3C%2FResponse%3E","To":"%2B919900299477","From":"%2B919900299477","Method":"POST","FallbackMethod":"POST","StatusCallbackMethod":"POST","Record":"false"}
Here's the source code:
JSONObject jsonObject = new JSONObject();
jsonObject.put("Url", "http://twimlets.com/echo?Twiml=" + URLEncoder.encode(
"<Response><Say voice=\"alice\" language=\"en-IN\">"
+ psMessage + "</Say></Response>", "UTF-8"));
jsonObject.put("To", URLEncoder.encode(psNumberToCall, "UTF-8"));
jsonObject.put("From", URLEncoder.encode("+919988776655", "UTF-8"));
jsonObject.put("Method", "POST");
jsonObject.put("FallbackMethod", "POST");
jsonObject.put("StatusCallbackMethod", "POST");
jsonObject.put("Record", "false");
Log.i(getClass().getName(), "JSON Object: " + jsonObject.toString());
HttpClient httpClient = new DefaultHttpClient();
String sUrl = "https://api.twilio.com/2010-04-01/Accounts/AC****/Calls.json";
HttpPost httpPost = new HttpPost(sUrl);
StringEntity se = new StringEntity(jsonObject.toString());
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("content-type", "application/json");
String authString = "Basic " + Base64.encodeToString
((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", authString);
Log.i(getClass().getName(), "HttpPost: " + httpPost.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream is = httpResponse.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sbResp = new StringBuilder();
String sLine = "";
while((sLine = br.readLine()) != null){
sbResp.append(sLine);
}
is.close();
return sbResp;
I could solve this myself. Posting it for the benefit of others in case if they face the same problem:
The request is simple post method. Response can be JSON / XML etc.,
Here's the working code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(sTwilioUrl);
List<NameValuePair> paramsList = new ArrayList<NameValuePair>(3);
paramsList.add(new BasicNameValuePair("To", psNumberToCall));
paramsList.add(new BasicNameValuePair("From", "+919988776655"));
paramsList.add(new BasicNameValuePair("Url", sVoiceUrl));
httpPost.setEntity(new UrlEncodedFormEntity(paramsList));
//httpPost.setHeader("Accept", "application/json");
//httpPost.setHeader("content-type", "application/json");
String authString = "Basic " + Base64.encodeToString
((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", authString);
HttpResponse httpResponse = httpClient.execute(httpPost);
return EntityUtils.toString(httpResponse.getEntity());
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.
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.