HTTP POST with json - wrong parameters - java

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();

Related

How to get only Json content from HttpEntity Java

Using HttpEntity I am getting a very long text which has special characters as well along with Json.
I tried regex but it's not working as it is almost 30000 of characters.
Is there a way that i can only get Json data from the HttpEntity. Even string split did not work since it has so many of special characters.
public JSONObject sendGet(String URL, String userName, String password) throws Exception {
getRequest = new HttpGet(URL);
getRequest.addHeader("User-Agent", USER_AGENT);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
provider.setCredentials(AuthScope.ANY, credentials);
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
outputFile = new File(directoryPath + "/target/response.txt");
fos = new FileOutputStream(outputFile);
headers = response.getAllHeaders();
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (Header header: headers) {
bw.write(header.getName() + ": " + header.getValue() + "\n");
}
bw.write(response.getEntity());
bw.write("Response Code : " + response.getStatusLine());
String content = EntityUtils.toString(entity); //When i print content it has string other than json as well
JSONObject obj = new JSONObject(content); //Here i receive A JSONObject text must begin with '{' at 1 [character 2 line 1]
JSONArray keys = obj.names();
Object test = JSON.parse(content);
jsonFiles = new File(directoryPath + "/JsonFiles/test.json");
fos = new FileOutputStream(jsonFiles);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
bw.close();
return obj;
}
Try adding the following Headers:
getRequest.addHeader("Accept", "application/json");
getRequest.addHeader("Content-Type", "application/json");
getRequest.addHeader("Accept-Charset", "utf-8");

Can't pass request parameters using http post

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

Problems with setting Authorization in request headers from Java

I am facing a problem where I am not able to set the "Authorization" Header.
I am Able to set the rest of the headers but when I am using the particular Key I am not able to set any data. Please help.
URL myURL = new URL(url);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String basicAuth = "Bearer 6f6b06fe-131e-314b-9ef8-42f2cbdcfc18";
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setRequestProperty("Authorization", "basicAuth");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
System.out.println(myURLConnection.getRequestProperties());
Hoping to hear soon. Thank you.
The statement
myURLConnection.getRequestProperties()
does not list all headers.
By looking at the source of HttpURLConnection you notice Authorization is part of the headers excluded by HttpURLConnection#getRequestProperties.
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/484e16c0a040/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java
This does not mean the header isn't set.
I think You made a little mistake there, The value for the key Authorization must not be "basicAuth". So please replace the code with :
myURLConnection.setRequestProperty("Authorization", basicAuth);
Or try this :
String basicAuth = "Bearer 6f6b06fe-131e-314b-9ef8-42f2cbdcfc18";
String encodedAuth= Base64.encode(basicAuth.getBytes());
myURLConnection.setRequestProperty("Authorization", encodedAuth);
Try with following code:
public void sendPost(String URL, String jsonData, String authUrl) throws Exception {
post = new HttpPost(URL);
// add header
post.setHeader("Authorization", accessToken);
post.setHeader("User-Agent", USER_AGENT);
if (!jsonData.isEmpty()) {
post.setEntity(new StringEntity(jsonData, ContentType.create("application/json")));
}
client = HttpClientBuilder.create().build();
response = client.execute(post);
outputFile = new File("path of file");
fos = new FileOutputStream(outputFile);
headers = response.getAllHeaders();
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (Header header : headers) {
bw.write(header.getName() + ": " + header.getValue() + "\n");
}
bw.write("Response Code : " + response.getStatusLine());
bw.close();
}

JSON / Java / Twilio response: "No 'To' number is specified" when request sent from JSON

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());

Encode params used within a post

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.

Categories

Resources