How to get a plain http request - servlets

a third party service says my service is miss configures
how can I get the plain text of a request on a servlet? I need to show what my service is well configured
any idea?
[Edit] here code:
System.out.println(request.getMethod() + " " + request.getPathInfo() + "" + request.getProtocol());
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println(headerName + ": " + request.getHeader(headerName));
}
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.print(paramName+"="+request.getParameter(paramName));
if(params.hasMoreElements()){
System.out.print("&");
}
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);

To be sure, nothing beats a packet sniffer such as Wireshark. Take the time to install it and learn how to use it - it will save you a lot of time when doing web development.

Related

SMS application is not sending special characters asp.net mvc

I have an ASP.NET MVC application that sends SMS from the web, problem is it doesn't send some special characters such as ~!##$&, when I send something like &&&&, it doesn't send SMS, if I send something like dan&dan it will send the first dan and remove remaining character and word.
Hare is my code:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + mess + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
Hope someone can assist.
Because you use Get method to call SMS web service, illegal characters automatically removed from your SMS. You need to use HttpUtility.UrlEncode to encode characters before sending.
Thanks so much for the light, i manage to find a solution using HttpUtility.UrlEncode:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string message = HttpUtility.UrlEncode(mess, System.Text.Encoding.GetEncoding("ISO-8859-1"));
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + message + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}

Tableau Unexpired Trusted Ticket - including ClientIP

I have an ASP.NET web application in which I'm rendering different tableau dashboards from a site based on the menu clicked by the user. I have multiple menus and each menu was tied to a tableau URL.
Tableau Trusted Authentication has been implemented to get the trusted ticket from the tableau server. Once the ticket has been retrieved, I am appending the ticket to the dashboard URL along with the server name for each menu.
The trusted ticketing module is working fine and the visualizations are getting rendered in my web application. However, frequently I am getting a message of "Could not locate unexpired ticket" error.
On checking with this error, this is due to the ticket calls getting duplicated.
I reached out to the support regarding this and got a response that I can add client_ip during my trusted ticketing.
Tableau Trusted Ticket
I am not able to find any code article related to adding client_ip in trusted ticketing.
Below is my trusted ticket code.
public class TableauTicket
{
public string getTableauTicket(string tabserver, string sUsername)
{
try
{
ASCIIEncoding enc = new ASCIIEncoding();
string postData = string.Empty;
string resString = string.Empty;
postData = "username=" + sUsername + "";
// FEATURE 816 END - Custom Visualization - KV
if (postData != string.Empty)
{
byte[] data = enc.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
req.ContentLength = data.Length;
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(stream: res.GetResponseStream(), encoding: enc);
resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
else
{
resString = "User not authorised";
return resString;
}
}
catch (Exception ex)
{
string resString = "User not authorised";
return resString;
string strTrailDesc = "Exception in tableau ticket - " + ex.Message;
}
}
public int Double(int i)
{
return i * 2;
}
}
Can anyone please let me know how the client_ip can be passed in trusted ticketing code?
Also, the client IP will get changed for each user and how this will be handled in the trusted ticketing?
UPDATE
I have solved the issue using the source code provided by tableau on how to embed the view in SharePoint.
Below is the code which may help users having the same issue.
string GetTableauTicket(string tabserver, string tabuser, ref string errMsg)
{
ASCIIEncoding enc = new ASCIIEncoding();
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
string postData = "username=" + tabuser + "&client_ip=" + Page.Request.UserHostAddress;
byte[] data = enc.GetBytes(postData);
try
{
string http = _tabssl ? "https://" : "http://";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(http + tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// Write the request
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
// Do the request to get the response
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(res.GetResponseStream(), enc);
string resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
// if anything bad happens, copy the error string out and return a "-1" to indicate failure
catch (Exception ex)
{
errMsg = ex.ToString();
return "-1";
}
}
Assuming your code is working, (I have done this part in Java and not really an expert in asp.net) all you have to do is to add something like:
postData = postData +"&client_ip=" +<variable for client IP>;
The way it is handled on tableau server is :
you turn on wgserver.extended_trusted_ip_checking on Tableau server. see details here
Tableau will match the client IP you passed in the POST request 'client_ip=XXX.XXX.XXX.XXX' while obtaining the token, with the actual IP of the the machine where the browser is trying to access tableau server.

HTTP POST receiving more than one HTTP Response

I have an http POST being actioned via a .NET System.Net.WebRequest as follows:
...
XXXUtilities.Log.WriteLog(string.Format("XXXHTTPPost PostToUri has uri={0}, body={1}", uri, messageBodyAsString));
System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(messageBodyAsString);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string rs = sr.ReadToEnd().Trim();
sr.Close();
resp.Close();
XXXUtilities.Log.WriteLog(string.Format("XXXHTTPPost PostToUri has string response = {0}", rs));
MongoDB.Bson.BsonDocument doc2 = new BsonDocument();
doc2.Add("Response", rs);
return doc2;
}
}
catch (System.Net.WebException e)
{...
This all works fine most of the time. However, looking at the log files that this creates I spotted something strange. The suspect log entries look like this:
18:59:17.0608 HPSHTTPPost PostToUri has uri=https://salesforce.ringlead.com/cgi-bin/2848/3/dedup.pl, body=LastName=Doe&FirstName=Jon
18:59:17.5608 HPSHTTPPost PostToUri has string response = Success
18:59:18.0295 HPSHTTPPost PostToUri has string response = Success
It seems that the Http Response is being received twice. Is this even technically possible? i.e. is it possible for an Http POST to receive two Responses, one after the other? If so, is my code below then liable to be called twice, thus resulting in the observed log file entries? Many thanks.
Edit:
In response to the comment that the logging code may be broken, here is the logging code:
public class Log
{
public static void WriteLog(string commandText)
{
string clientDBName = "test";
string username = "test";
try
{
string filePath = "c:\\Data\\XXXLogs\\" + clientDBName + "logs\\";
string filename = System.DateTime.Now.ToString("yyyyMMdd_") + username + ".log";
DirectoryInfo dir = new DirectoryInfo(filePath);
if (!dir.Exists)
{
dir.Create();
}
System.IO.FileStream stream = new System.IO.FileStream(
filePath + filename
, System.IO.FileMode.Append); // Will create if not already exists
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(); // Writes a line terminator, thus separating entries by 1 blank line
writer.WriteLine(System.DateTime.Now.ToString("HH:mm:ss.ffff") + " " + commandText);
writer.Flush();
stream.Close();
}
catch { }
}
}

File created insted of Folder in Alfresco

I am trying to create a folder in Alfresco using XMSI below is the code i am using .
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
String host = "127.0.0.1";
int port = 9080;
String username = "admin";
String password = "admin";
String parentFolder = "Company%20Home";
String folderName = "sales3";
String description = "sales space3";
RulesRequest request = new RulesRequest();
//request.setRemediationProfileObj(remediationProfile);
Gson gs = new Gson();
String json = gs.toJson(request);
DefaultHttpClient client = new DefaultHttpClient();
RestClient rstClnt = new RestClient();
String ticket = rstClnt.restClientPost(json, "http://127.0.0.10:9080/alfresco/service/api/login?u=admin&pw=admin", client);
//String url = "http://" + host + ":" + port + "/alfresco/service/api/path/workspace/SpacesStore/" + parentFolder + "/children";
String url = "http://localhost:9080/alfresco/service/cmis/s/workspace:SpacesStore/i/078b05c6-14bd-439c-a1ae-db032c5d98fc/children?alf_ticket="+ticket;
String contentType = "application/atom+xml;type=entry";
String xml =
"<?xml version='1.0' encoding='utf-8'?>\n" +
"<entry xmlns='http://www.w3.org/2005/Atom' xmlns:cmis='http://www.cmis.org/2008/05'>\n" +
"<title>" + folderName + "</title>\n" +
"<summary>" + description + "</summary>\n" +
"<cmis:object>\n"+
"<cmis:properties>\n" +
"<cmis:propertyString cmis:name='cmis:objectTypeId'>\n" +
"<cmis:value>cmis:folder</cmis:value>\n" +
"</cmis:propertyString>\n" +
"</cmis:properties>\n" +
"</cmis:object>\n" +
"</entry>\n";
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", contentType);
StringEntity requestEntity = new StringEntity(xml, "UTF-8");
httppost.setEntity(requestEntity);
System.out.println("executing request" + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content type: " + entity.getContentType());
long contentLength = entity.getContentLength();
System.out.println("Response content length: "
+ entity.getContentLength());
if (contentLength > 0) {
byte [] b = new byte[(int) contentLength];
entity.getContent().read(b);
System.out.println("Response content: " + new String(b));
}
entity.writeTo(System.out);
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
long end = System.currentTimeMillis();
System.out.println("Time spend: " + (end-start) + "ms");
}
Instead of creating a folder it is creating a file of size 0.
Thanks
Garvit
Your property is of the wrong type. You are incorrectly using cmis:propertyString instead of cmis:propertyId Try the following
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">
<cmis:value>cmis:folder</cmis:value>
</cmis:propertyId>
As #Gagravarr says, problems like this are easily avoided if you can use well-known client libraries. If you are constructing the HTTP requests yourself you'd better have a good reason for that.

Paypal with express checkout to get BillingAgreementID

I am working with the paypal using express checkout to get a billing agreement id.
I was following this guide:
https://www.x.com/developers/paypal/documentation-tools/how-authorize-and-run-reference-transaction-express-checkout
In the first step when i do "SetExpressCheckout":
The following is the code
public string SetExpressCheckout(string Amount)
{
string returnURL = "http://localhost:50325/ReviewOrder.aspx" + "?amount=" + Amount + "&PAYMENTREQUEST_0_CURRENCYCODE=USD";
string cancelURL = returnURL.Replace("ReviewOrder", "ExpCheckOut");
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
string strNVP = strCredentials;
strNVP += "&PAYMENTREQUEST_0_PAYMENTACTION=AUTHORIZATION&&PAYMENTREQUEST_0_AMT=25" + "&L_BILLINGTYPE0=MerchantInitiatedBilling" + "&RETURNURL=" + returnURL;
strNVP += "&CANCELURL=" + cancelURL;
strNVP += "&METHOD=SetExpressCheckout&VERSION=" + strAPIVersion + "&DESC=test EC payment" +"&NOSHIPPING=0" ;
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
//Set WebRequest Properties
wrWebRequest.Method = "POST";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
// and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
The response is:
TOKEN=EC-09082530FY878870B&
TIMESTAMP=2013-03-25T00:45:56Z&
CORRELATIONID=3d33037174d55&
ACK=SuccessWithWarning&
VERSION=86&
BUILD=5479129&
L_ERRORCODE0=11452&
L_SHORTMESSAGE0=Merchant not enabled for reference transactions&
L_LONGMESSAGE0=Merchant not enabled for reference transactions&
L_SEVERITYCODE0=Warning
How to to get a BillingAgreeentd in Step 3:
Code for step 3 is:
public string GetBillingAgreementID()
{
string returnURL = "http://localhost:50325/ReviewOrder.aspx" + "?amount=" + Amount + "¤cy=USD";
string cancelURL = returnURL.Replace("ReviewOrder", "ExpCheckOut");
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
string strNVP = strCredentials;
strNVP += "&RETURNURL=" + returnURL;
strNVP += "&CANCELURL=" + cancelURL;
strNVP += "&METHOD=CreateBillingAgreement&VERSION=" + strAPIVersion + "&TOKEN=" + Session["Token"];
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
//Set WebRequest Properties
wrWebRequest.Method = "POST";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
// and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
Response is:
TIMESTAMP=2013-03-25T00:51:34Z&
CORRELATIONID=854e6beed1e82&
ACK=Failure&
VERSION=86&
BUILD=5479129&
L_ERRORCODE0=11455&
L_SHORTMESSAGE0=Buyer did not accept billing agreement&
L_LONGMESSAGE0=Buyer did not accept billing agreement&
L_SEVERITYCODE0=Error
How to get a BillingAgreemntId?
Is that because of "L_SHORTMESSAGE0=Merchant not enabled for reference transactions" this message from "SetExpressCheckout" am i not able to get BillingAgreementID?
Please help me on this. Thanks.
You would need to contact PayPal and request this to be enabled on the account, if this is for a live account. If you are needing it enabled on the sandbox, you would need to contact PayPal MTS and have this enabled on your sandbox account.

Resources