Resttemplate Returns 500 Response Message - resttemplate

I am trying to make a post request which is supposed to return a json, but for some reason it returns 500 something went wrong.
'''
public void templatRequestPayment(String token, String url, String key, String body)
throws RestClientException, URISyntaxException, IOException {
URI uri = new URI(url);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", token);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("key", key);
HttpEntity<String> entity = new HttpEntity<String>(body, headers);
RestTemplate template = new RestTemplate(getConverter());
try {
ResponseEntity<JsonNode> res = template.exchange(uri, HttpMethod.POST, entity,
JsonNode.class);
String tok = res.getBody().toString();
System.out.println(tok);
} catch (HttpStatusCodeException e) {
ResponseEntity<String> st =
ResponseEntity.status(e.getStatusCode()).headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
System.out.println(st.getHeaders() + "-- /n" + st.getBody());
}
}
protected List<HttpMessageConverter< ?>> getConverter() {
List<HttpMessageConverter< ?>> converters = Lists.newArrayList();
converters.add(new MappingJackson2HttpMessageConverter());
return converters;
}
'''

Related

Blank CSV file generated,need to write data stored inside List<List<Object>

I need to create and download the CSV file, and for this I am using OpenCSV with Spring MVC, the data need to be written is holding by my class name CsvDataDto.
public class CsvDataDto {
private String fileName;
List<String> header=new ArrayList<>();;
private String heading;
List<List<Object>> data=new ArrayList<>();
//getters and setters
}
The main data contains file header (eg: userid,fname,lastname,rollno) and actual data (eg. 1,101,john,doe,1001).
File header is hold by List<String> header
and The file data is hold by List<List<Object>> data
and here is the controller method which set all the required data
#RequestMapping(value = "/export_data")
public void downloadDataInCsv(
#RequestParam("type") String type,
#RequestParam("tID") String tableId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (type.equals("csv")) {
CsvDataDto dataDTO = new CsvDataDto();
dataDTO.setFileName("Table_Data");
dataDTO.getHeader().add("User Id");
dataDTO.getHeader().add("First Name");
dataDTO.getHeader().add("Last Name");
dataDTO.getHeader().add("Roll No");
dataDTO.getHeader().add("Email ID");
dataDTO.getHeader().add("Gender");
List<UserInfo> list = userInfoDao.findById(tableId);
for (UserInfo infoList : list) {
List<Object> newList = new ArrayList<>();
newList.add(infoList.getUserId());
newList.add(infoList.getFirstName());
newList.add(infoList.getLastName());
newList.add(infoList.getRollNo());
newList.add(infoList.getEmail());
newList.add(infoList.getGender());
dataDTO.getData().add(newList);
}
ExportCsvUtil.downloadCsv(request, response, dataDTO);
}
Now the downloadCsv() implementation
public static void downloadCsv(HttpServletRequest request, HttpServletResponse response, CsvDataDto csvDataDto) throws IOException {
List<String[]> records = new ArrayList<>();
String csvFileName = csvDataDto.getFileName();
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=" + csvDataDto.getFileName() + ".csv");
response.setContentType("text/csv");
response.setHeader(headerKey, headerValue);
CSVWriter writer = new CSVWriter(new FileWriter(csvFileName));
String[] headerArr = new String[csvDataDto.getHeader().size()];
headerArr = csvDataDto.getHeader().toArray(headerArr);
records.add(headerArr);
for (List<Object> objList : csvDataDto.getData()) {
System.out.println("object list:" + objList);
String[] fileData = new String[objList.size()];
fileData = objList.toArray(fileData);
records.add(fileData);
}
writer.writeAll(records);
writer.close();
System.out.println(writer);
}
}
I am stuck here,as I explore tons of examples where the instructors simple pass the data in writeNext() method.
writer.writeNext(csvDataDto);
But I know that it will not work as i expected.File is successfully downloaded but blank, no data is write over it.
I want to implement the logic in such a way, so I get the CSV like below
userid, fname,lastname,rollno,gender (List<String> header)
1 , john, doe ,1001, M (List<List<Object>> data)
2 , Rose, Mary ,1002, F
3 , Jack, Jill ,1003, M
What is the best way to achieve the same by using writeNext().
#RequestMapping(value = "/export_data")
public void downloadDataInCsv(
#RequestParam("type") String type,
#RequestParam("tID") String tableId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (type.equals("csv")) {
List<UserInfo> list = userInfoDao.findById(tableId);
ExportCsvUtil.downloadCsv(request, response, list);
}
}
private void downloadCsv(HttpServletRequest request, HttpServletResponse response, List<UserInfo> list) throws IOException {
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=Table_Data.csv");
response.setContentType("text/csv");
response.setHeader(headerKey, headerValue);
try (final CSVWriter writer = new CSVWriter(response.getWriter(), ",")) {
writer.writeNext(new String[]{"User Id", "First Name", "Last Name", "Roll No", "Email ID", "Gender"});
for (UserInfo entry: list) {
// cast/convert to String where needed
writer.writeNext(new String[]{entry.getUserId()+"", entry.getFirstName(), entry.getLastName(),entry.getRollNo(),entry.getEmail(),entry.getGender()});
}
writer.close();
}
}

How to get data from servlet by extjs

i create an jsonarray and sent from servlet, and sent to the front side,
the front side should get the message and currentTime, and show them in the website. How should i do that in EXTjs:
Here is the code in the servelet:
public void loadHistory(HttpServletRequest request, HttpServletResponse response) throws IOException{
JsonObject json = new JsonObject();
JsonArray dataArray = new JsonArray();
String groupName = request.getParameter("groupName");
String chatRoomName = getChatRoom(groupName);
Database db = new Database(chatRoomName);
CouchDbClient dbClient = db.getDbClient();
PrintWriter out = response.getWriter();
int i=0;
while (dbClient.contains(String.valueOf(i++))){
JsonObject objHistory = dbClient.find(JsonObject.class, String.valueOf(i++));
String preMessage = objHistory.get("message").getAsString();
String preTime = objHistory.get("currentTime").getAsString();
json.addProperty("message", preMessage);
json.addProperty("currentTime", preTime);
dataArray.add(json);
}
if (dataArray!=null){
response.setContentType("application/json");
out.print(dataArray);
out.close();
}
}
modify the below code in the if conditon before sending the response.
if (dataArray!=null){
response.setContentType("application/json");
JSONObject resultJsonMain=new JSONObject();
resultJsonMain.put("resultJsonMain",dataArray);
out.println(resultJsonMain);
out.close();
}

POST data to XML service aspx vb

Dim doc As New XmlDocument
doc.Load("http://www.example.com/?paramx=1&paramy=2")
is great for GET queries in the querystring. But say I wanted to POST the paramx=1&paramy=2 to http://www.example.com and get the response in XML. How would I do that?
Below is a helper class I use for POSTing data to a website which then returns XML - hope it helps.
Usage:
var resultXmlDoc = new HttpHelper().PostXml("http://www.test.com", new { paramName = "value", paramName2="value2" });
Helper class:
internal class HttpHelper
{
public XDocument PostXml(string baseUrl, IDictionary<string, string> cgiParams)
{
return XDocument.Load(Post(baseUrl, cgiParams).GetResponseStream());
}
public XDocument PostXml(string baseUrl, params object[] items)
{
return XDocument.Load(Post(baseUrl, items).GetResponseStream());
}
public XDocument PostXml(string url, string topost)
{
return XDocument.Load(Post(url, topost).GetResponseStream());
}
protected virtual HttpWebResponse Post(string url, string postString)
{
if (url == null)
throw new ArgumentNullException("baseUrl");
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
throw new ArgumentException("url is not a valid Uri");
var req = (HttpWebRequest)WebRequest.Create(url);
// if the target site issues a session cookie, you need to store it and append it here
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
var bytes = System.Text.Encoding.ASCII.GetBytes(postString);
req.ContentLength = bytes.Length;
using(var str = req.GetRequestStream())
str.Write(bytes, 0, bytes.Length);
return (HttpWebResponse)req.GetResponse();
}
protected virtual HttpWebResponse Post(string url, params object[] items)
{
var x = items.SelectMany(i =>
{
return i.GetType().GetProperties().Select(p => new Tuple<string, string>(p.Name, p.GetValue(i, null) != null ? p.GetValue(i, null).ToString() : ""));
});
var d = new Dictionary<string, string>();
foreach (var p in x)
d[p.Item1] = p.Item2;
return Post(url, d);
}
protected virtual HttpWebResponse Post(string baseUrl, IDictionary<string, string> cgiParams)
{
if (baseUrl == null)
throw new ArgumentNullException("baseUrl");
Uri uri;
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out uri))
throw new ArgumentException("baseUrl is not a valid Uri");
string postString = string.Empty;
if (cgiParams != null && cgiParams.Count > 0)
{
foreach (var k in cgiParams.Keys)
postString += HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(cgiParams[k]) + "&";
postString = postString.Substring(0, postString.Length - 1);
}
return Post(baseUrl, postString);
}
}

Problems sending and receiving JSON between ASP.net web service and ASP.Net web client

You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem,
If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error
The Web Service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
Dim Someone As New Person
Someone.Name = "Bob"
Someone.FavoriteColor = "Green"
Someone.ID = WebInfo.WebUserID.ToString()
Return Someone
End Function
The Web Client (set up to be send and receive JSON)
public Person Test(int UserID, string url) {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write("{'WebInfo':{'WebUserID':1}}"); // this works from JQuery
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
Person someone = (Person)jsonSerializer.ReadObject(responseStream);
return someone;
}
Has anyone out there done this successfully?
Thanks
Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below
public class WebServiceCallReturn {
public string JSONResponse { get; set; }
public string SimpleResponse { get; set; }
public string Error { get; set; }
}
public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
WebServiceCallReturn result = new WebServiceCallReturn();
// create request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = requestType;
webRequest.Accept = "application/json; charset=utf-8";
// add json data object to send
if (requestType == "POST") {
string json = "{ }";
if (postData != null) {
try { // the serializer is fairly robust when used this way
DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, postData);
json = Encoding.UTF8.GetString(ms.ToArray());
} catch {
result.Error = "Error serializing post";
}
}
webRequest.ContentLength = json.Length;
StreamWriter sw;
try {
sw = new StreamWriter(webRequest.GetRequestStream());
} catch (Exception ex) {
// the remote name could not be resolved
result.Error = ex.Message;
return result;
}
sw.Write(json);
sw.Close();
}
// read response
HttpWebResponse webResponse;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (Exception ex) {
// The remote server returned an error...
// (400) Bad Request
// (403) Access forbidden (check the application pool)
// (404) Not Found
// (405) Method not allowed
// (415) ...not the expected type
// (500) Internal Server Error (problem with IIS or unhandled error in web service)
result.Error = ex.Message;
return result;
}
Stream responseStream = webResponse.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string resultString = sr.ReadToEnd();
sr.Close();
responseStream.Close();
result.JSONResponse = resultString;
return result;
}
This method could be used as follows
public SomeCustomDataClass Getsomeinformation(int userID) {
UserInfoClass postData = new UserInfoClass();
postData.WebUserID = userID;
SomeCustomDataClass result = new SomeCustomDataClass();
string uri = URL + "SomeServices.svc/GetSomething";
WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
if (webReturn.Error == null) {
//resultString = CleanJSON(resultString);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try {
result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
} catch {
result.Error = "Error deserializing";
}
} else {
result.Error = webReturn.Error;
}
return result;
}
Hope that helps someone

Google voice call error

namespace GoogleVoiceCall
{
class Program
{
private const string LOGIN_URL = "https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral";
private const string GOOGLE_VOICE_HOME_URL = "https://www.google.com/voice";
private const string CALL_URL = "https://www.google.com/voice/call/connect";
private static string m_emailAddress = "your email address";
private static string m_password = "password";
private static string m_gizmoNumber = "your gizmo number";
private static string m_destinationNumber = "your destination number";
static void Main(string[] args)
{
try
{
Console.WriteLine("Attempting Google Voice Call");
CookieContainer cookies = new CookieContainer();
// First send a login request to get the necessary cookies.
string loginData = "Email=" + Uri.EscapeDataString(m_emailAddress)
+ "&Passwd=" + Uri.EscapeDataString(m_password);
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
loginRequest.CookieContainer = cookies;
loginRequest.AllowAutoRedirect = true;
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
loginRequest.ContentLength = loginData.Length;
loginRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(loginData), 0, loginData.Length);
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
if (loginResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Login failed.");
}
else
{
Console.WriteLine("Login request was successful.");
}
// Second send a request to the Google Voice home page to get a string key needed when placing a callback.
HttpWebRequest keyRequest = (HttpWebRequest)WebRequest.Create(GOOGLE_VOICE_HOME_URL);
keyRequest.CookieContainer = cookies;
HttpWebResponse keyResponse = (HttpWebResponse)keyRequest.GetResponse();
if (keyResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("_rnr_se key request failed.");
}
else
{
Console.WriteLine("Key request was successful.");
}
StreamReader reader = new StreamReader(keyResponse.GetResponseStream());
string keyResponseHTML = reader.ReadToEnd();
Match rnrMatch = Regex.Match(keyResponseHTML, #"name=""_rnr_se"".*?value=""(?<rnrvalue>.*?)""");
if (!rnrMatch.Success)
{
throw new ApplicationException("_rnr_se key was not found on your Google Voice home page.");
}
string rnr = rnrMatch.Result("${rnrvalue}");
Console.WriteLine("_rnr_se key=" + rnr);
// Thirdly (and lastly) submit the request to initiate the callback.
string callData = "outgoingNumber=" + Uri.EscapeDataString(m_destinationNumber) +
"&forwardingNumber=" + Uri.EscapeDataString(m_gizmoNumber) +
"&subscriberNumber=undefined&remember=0&_rnr_se=" + Uri.EscapeDataString(rnr);
HttpWebRequest callRequest = (HttpWebRequest)WebRequest.Create(CALL_URL);
callRequest.CookieContainer = cookies;
callRequest.Method = "POST";
callRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
callRequest.ContentLength = callData.Length;
callRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(callData), 0, callData.Length);
HttpWebResponse callResponse = (HttpWebResponse)callRequest.GetResponse();
if (callResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Call request failed.");
}
else
{
Console.WriteLine("Call request was successful.");
}
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp.Message);
}
finally
{
Console.WriteLine("finished, press any key to exit...");
Console.ReadLine();
}
}
}
}
I have used the above codes for make a call like Googl voice call using Google voicall service, but i am getting an error. error is
_rnr_se key was not found
pelase tell here what are this
m_gizmoNumber and _rnr_se key
add this line before login request :
m_cookies.Add(new Uri(PRE_LOGIN_URL), galxResponse.Cookies);
see here .

Resources