IdHTTP how to send raw body - http

How i can use IdHTTP to send message as PostMan dos below:
My first attempt was as follow:
function TIdFoo.SendIM(const AID, AMessage: string): Boolean;
const
_URL = 'https://URL.com/SendMessage';
var
Params : TStringStream;
Response : string;
LMsg : string;
begin
Result := False;
LMsg := '-----------------------------13932'+
'Content-Type: application/json; charset=utf-8'+
'Content-Description: message'+ sLineBreak+ '{"message":{"Type":1,"body":"'+AMessage+'"},"to":["'+AID+'"]}'+
'-----------------------------13932--;'+sLineBreak;
Params := TStringStream.Create(LMsg, TEncoding.UTF8);
try
IdHTTP.Request.CustomHeaders.AddValue('authorization', 'Bearer ' + FToken);
IdHTTP.Request.CustomHeaders.AddValue('Origin', 'https://www.URL.com');
IdHTTP.Request.UserAgent := 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36';
IdHTTP.Request.Accept := '*/*';
IdHTTP.Request.Referer := 'https://www.URL.com/en-us/';
IdHTTP.Request.Host := 'URL.com';
IdHTTP.Request.AcceptEncoding := 'gzip, deflate, br';
IdHTTP.Request.AcceptLanguage := 'Accept-Language';
IdHTTP.Request.ContentType := 'multipart/mixed; boundary="---------------------------13932"';
Params.Position := 0;
try
Response := IdHTTP.Post(_URL, Params);
Result := True;
except
on E: Exception do
Writeln('Error on Send Message request: '#13#10, e.Message);
end;
Writeln(IdHTTP.Request.RawHeaders.Text);
finally
Params.Free;
end;
end;
The second attempt i try it this way
function TIdFoo.SendIM(const AID, AMessage: string): Boolean;
const
_URL = 'https://URL.com/SendMessage';
var
Params : TStringStream;
Response : string;
LMsg : string;
begin
Result := False;
LMsg := '{"message":{"Type":1,"body":"'+AMessage+'"},"to":["'+AID+'"]}';
Params := TStringStream.Create(LMsg, TEncoding.UTF8);
try
IdHTTP.Request.CustomHeaders.AddValue('authorization', 'Bearer ' + FToken);
IdHTTP.Request.CustomHeaders.AddValue('Origin', 'https://www.URL.com');
IdHTTP.Request.CustomHeaders.AddValue('Content-Description', 'message'); // I addedd this as on PostMan Body
IdHTTP.Request.UserAgent := 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36';
IdHTTP.Request.Accept := '*/*';
IdHTTP.Request.Referer := 'https://www.URL.com/en-us/';
IdHTTP.Request.Host := 'URL.com';
IdHTTP.Request.AcceptEncoding := 'gzip, deflate, br';
IdHTTP.Request.AcceptLanguage := 'Accept-Language';
IdHTTP.Request.ContentType := 'application/json; charset=utf-8'; // I alos changed this as it shown on PostMan body
Params.Position := 0;
try
Response := IdHTTP.Post(_URL, Params);
Result := True;
except
on E: Exception do
Writeln('Error on Send Message request: '#13#10, e.Message);
end;
Writeln(IdHTTP.Request.RawHeaders.Text);
finally
Params.Free;
end;
end;
Both attempts gives HTTP/1.1 400 Bad Request.
Can any advice my what i', doing wrong?

In your first example, your "raw" MIME data is not formatted correctly:
You are missing a bunch of required line breaks. And don't use the sLineBreak constant, as its value is platform-specific. MIME expects line breaks to use CRLF specifically. Indy has an EOL constant for that value.
You have an erroneous semicolon on the end of the closing boundary line.
You are also not setting the Request.AcceptEncoding property correctly. DO NOT enable encodings manually, unless you are prepared to actually handle them manually in responses (which your code is not). TIdHTTP handles gzip and deflate encodings for you, if you assign a TIdZLibCompressorBase-derived component, like TIdCompressorZLib, to the TIdHTTP.Compressor property. Don't worry about the br encoding, it is not widely used. In short, leave the Request.AcceptEncoding at its default and let TIdHTTP manage it for you.
You are also not setting the Request.AcceptLanguage property correctly. You should be setting it to 'en-US,en;q=0.8', not to 'Accept-Language'.
Your first example should work if you make these fixes, eg:
function TIdFoo.SendIM(const AID, AMessage: string): Boolean;
const
_URL = 'https://URL.com/SendMessage';
var
Params : TStringStream;
Response : string;
LMsg : string;
begin
Result := False;
LMsg := '-----------------------------13932' + EOL +
'Content-Type: application/json; charset=utf-8' + EOL +
'Content-Description: message' + EOL +
EOL +
'{"message":{"Type":1,"body":"'+AMessage+'"},"to":["'+AID+'"]}' + EOL +
'-----------------------------13932--' + EOL;
Params := TStringStream.Create(LMsg, TEncoding.UTF8);
try
IdHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + FToken);
IdHTTP.Request.CustomHeaders.AddValue('Origin', 'https://www.URL.com');
IdHTTP.Request.UserAgent := 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36';
IdHTTP.Request.Accept := '*/*';
IdHTTP.Request.Referer := 'https://www.URL.com/en-us/';
IdHTTP.Request.Host := 'URL.com';
IdHTTP.Request.AcceptLanguage := 'en-US,en;q=0.8';
IdHTTP.Request.ContentType := 'multipart/mixed; boundary="---------------------------13932"';
try
Response := IdHTTP.Post(_URL, Params);
Result := True;
except
on E: Exception do
Writeln('Error on Send Message request: '#13#10, e.Message);
end;
Writeln(IdHTTP.Request.RawHeaders.Text);
finally
Params.Free;
end;
end;
Alternatively:
function TIdFoo.SendIM(const AID, AMessage: string): Boolean;
const
_URL = 'https://URL.com/SendMessage';
var
Params : TMemoryStream;
Response : string;
LMsg : string;
begin
Result := False;
Params := TMemoryStream.Create;
try
WriteStringToStream(Params, '-----------------------------13932' + EOL);
WriteStringToStream(Params, 'Content-Type: application/json; charset=utf-8' + EOL);
WriteStringToStream(Params, 'Content-Description: message' + EOL);
WriteStringToStream(Params, EOL);
WriteStringToStream(Params, '{"message":{"Type":1,"body":"'+AMessage+'"},"to":["'+AID+'"]}' + EOL, IndyTextEncoding_UTF8);
WriteStringToStream(Params, '-----------------------------13932--' + EOL);
Params.Position := 0;
IdHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + FToken);
IdHTTP.Request.CustomHeaders.AddValue('Origin', 'https://www.URL.com');
IdHTTP.Request.UserAgent := 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36';
IdHTTP.Request.Accept := '*/*';
IdHTTP.Request.Referer := 'https://www.URL.com/en-us/';
IdHTTP.Request.Host := 'URL.com';
IdHTTP.Request.AcceptLanguage := 'en-US,en;q=0.8';
IdHTTP.Request.ContentType := 'multipart/mixed; boundary="---------------------------13932"';
try
Response := IdHTTP.Post(_URL, Params);
Result := True;
except
on E: Exception do
Writeln('Error on Send Message request: '#13#10, e.Message);
end;
Writeln(IdHTTP.Request.RawHeaders.Text);
finally
Params.Free;
end;
end;
Alternatively:
function TIdFoo.SendIM(const AID, AMessage: string): Boolean;
const
_URL = 'https://URL.com/SendMessage';
var
Params : TMemoryStream;
Response : string;
LMsg : string;
begin
Result := False;
Params := TMemoryStream.Create;
try
with TStreamWriter.Create(Params, TEncoding.UTF8) do
try
NewLine := EOL;
WriteLine('-----------------------------13932');
WriteLine('Content-Type: application/json; charset=utf-8');
WriteLine('Content-Description: message');
WriteLine;
WriteLine('{"message":{"Type":1,"body":"'+AMessage+'"},"to":["'+AID+'"]}');
WriteLine('-----------------------------13932--');
finally
Free;
end;
Params.Position := 0;
IdHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + FToken);
IdHTTP.Request.CustomHeaders.AddValue('Origin', 'https://www.URL.com');
IdHTTP.Request.UserAgent := 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36';
IdHTTP.Request.Accept := '*/*';
IdHTTP.Request.Referer := 'https://www.URL.com/en-us/';
IdHTTP.Request.Host := 'URL.com';
IdHTTP.Request.AcceptLanguage := 'en-US,en;q=0.8';
IdHTTP.Request.ContentType := 'multipart/mixed; boundary="---------------------------13932"';
try
Response := IdHTTP.Post(_URL, Params);
Result := True;
except
on E: Exception do
Writeln('Error on Send Message request: '#13#10, e.Message);
end;
Writeln(IdHTTP.Request.RawHeaders.Text);
finally
Params.Free;
end;
end;
In your second example, your "raw" data is just the JSON by itself, not any MIME wrapping it. You are putting MIME headers in the HTTP headers, where they don't belong. This example will not work if the server expects MIME data and not just raw JSON data.
You are also making the same mistakes with the Request.AcceptEncoding and Request.AcceptLanguage properties.
Since you are posting data in MIME format, an easier way to handle this would have been to use Indy's TIdMultipartFormDataStream class instead, and let it handle the MIME formatting for you. However, that class does not currently support:
setting the stream's RequestContentType property to a custom value (in this case, 'multipart/mixed' instead of 'multipart/form-data'). Though, you can use an accessor class to accomplish this, since the FRequestContentType member is protected.
omitting the Content-Disposition: form-data header on individual fields. This might trip up servers that are not expecting form-data submissions.
specifying the Content-Description MIME header at all (see Add support for user-defined MIME headers in TIdMultipartFormDataStream in Indy's issue tracker on GitHub).
So you will have to continue resorting to formatting the MIME data manually. You just have to make sure you get it right.

Related

HTTP client can't fetch a page while other tools (wget/curl) can

The following code in Go can't fetch page, it gets 404 error, while code in another language (php+curl) has no issues with this page. What is a reason of such behaviour?
package main
import (
"fmt"
"net/http"
)
func main() {
client := http.Client {}
req, err := http.NewRequest("GET", "https://myhresschoolofmusic.com/", nil)
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
panic(err)
}
defer resp.Body.Close()
fmt.Printf("%#v\n", resp)
}
Output of this code
&http.Response{
Status:"404 Not Found",
StatusCode:404,
Proto:"HTTP/2.0",
ProtoMajor:2,
ProtoMinor:0,
Header:http.Header{"Content-Length":[]string{"1245"},
"Content-Type":[]string{"text/html"},
"Date":[]string{"Wed, 20 Jan 2021 06:44:22 GMT"},
"X-Powered-By":[]string{"ASP.NET"}},
....
Seems that page is very picky about User-Agent header and rejects Go net/http default value Go-http-client/1.1. With browser-like user agent value like:
req, err := http.NewRequest("GET", "https://myhresschoolofmusic.com", nil)
req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36")
it works just fine.

VerifyIDToken on Go SDK got panicked

I've no idea why the VerifyIDToken on Go SDK got panicked. I've used VerifyIDToken on the handler of gin as follows:
r.GET("/idToken/:id", func(c *gin.Context) {
// idToken := c.Param("id")
opt := option.WithCredentialsFile("xxx-secret.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
fmt.Println(fmt.Errorf("error initializing app: %v", err))
}
client, err := app.Auth(context.Background())
if err != nil {
fmt.Println("error getting Auth client: %v\n", err)
fmt.Println(client)
}
idToken := c.Param("id")
fmt.Println("idTaken = ", idToken)
token, err := client.VerifyIDToken(context.Background(), idToken)
if err != nil {
fmt.Println("error verifying ID token: %v\n", err)
}
fmt.Println("Verified ID token: %v\n", token)
})
I've called above API as follows:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
axios
.get('https://xx.xxx.com/idToken/' + idToken)
.then(response => {
this.response = response;
console.log(response);
if (response.data.update == "ok") {
this.acceptOKresponse = true;
}
})
}).catch(function(error) {
// Handle error
});
Then, Followings appeared on the server console:
idTaken = eyJhbGciOiJSUzI1NiIsImtpZCI6IjBlYTNmN2EwMjQ4YmU0ZTBkZjAyYWVlZWIyMGIxZDJlMmI3ZjI0NzQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi5LiK55Sw5YGl5LmLIiwiaXNzIjoiaHR0cHM6Ly9zZWN1cmV0b2tlbi5nb29nbGUuY29tL21hZ2ljbGFiZWwtYjQ0NjkiLCJhdWQiOiJtYWdpY2xhYmVsLWI0NDY5IiwiYXV0aF90aW1lIjoxNTgzMTE2MjQwLCJ1c2VyX2lkIjoiS0V5b3dYZnd4NFNqbEMwakdsTnVzcDU0c0xQMiIsInN1YiI6IktFeW93WGZ3eDRTamxDMGpHbE51c3A1NHNMUDIiLCJpYXQiOjE1ODMxMjM3NTcsImV4cCI6MTU4MzEyNzM1NywiZW1haWwiOiJnZGUwMDEwN0BuaWZ0eS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJnZGUwMDEwN0BuaWZ0eS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.ABnMA6iOITghzo_WzgdDwssODiLsswVSlKod6w5CHcnkJOQVKqQIynZufTQvcF8nQO77MYXikZD8TQE_uGq3EpHWQibun67mvN74GnPaguzgvpjQ-PqIOzuhnn2n2SpHSacdREtFkwtj1S66bhigbuTJbqr8jQtIEIB6gfmnObwcmpNRsc-GGR45xjWAO6UY4Ygw4xDcHsHGXwL6SA-HbDuSZGeQfXtdPt94taJfrQQB9nr_7gRjttQLz4ongh-g-fMSpWx3z8lmQgPwgg4GyChYPZ6_hdEV3AWFJTHptE2X8RCV6HfpZB6EGwvLQr6ZrC01uodGTg87BvtPrersjA
2020/03/02 13:35:58 [Recovery] 2020/03/02 - 13:35:58 panic recovered:
GET /idToken/eyJhbGciOiJSUzI1NiIsImtpZCI6IjBlYTNmN2EwMjQ4YmU0ZTBkZjAyYWVlZWIyMGIxZDJlMmI3ZjI0NzQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi5LiK55Sw5YGl5LmLIiwiaXNzIjoiaHR0cHM6Ly9zZWN1cmV0b2tlbi5nb29nbGUuY29tL21hZ2ljbGFiZWwtYjQ0NjkiLCJhdWQiOiJtYWdpY2xhYmVsLWI0NDY5IiwiYXV0aF90aW1lIjoxNTgzMTE2MjQwLCJ1c2VyX2lkIjoiS0V5b3dYZnd4NFNqbEMwakdsTnVzcDU0c0xQMiIsInN1YiI6IktFeW93WGZ3eDRTamxDMGpHbE51c3A1NHNMUDIiLCJpYXQiOjE1ODMxMjM3NTcsImV4cCI6MTU4MzEyNzM1NywiZW1haWwiOiJnZGUwMDEwN0BuaWZ0eS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJnZGUwMDEwN0BuaWZ0eS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.ABnMA6iOITghzo_WzgdDwssODiLsswVSlKod6w5CHcnkJOQVKqQIynZufTQvcF8nQO77MYXikZD8TQE_uGq3EpHWQibun67mvN74GnPaguzgvpjQ-PqIOzuhnn2n2SpHSacdREtFkwtj1S66bhigbuTJbqr8jQtIEIB6gfmnObwcmpNRsc-GGR45xjWAO6UY4Ygw4xDcHsHGXwL6SA-HbDuSZGeQfXtdPt94taJfrQQB9nr_7gRjttQLz4ongh-g-fMSpWx3z8lmQgPwgg4GyChYPZ6_hdEV3AWFJTHptE2X8RCV6HfpZB6EGwvLQr6ZrC01uodGTg87BvtPrersjA HTTP/1.1
Host: ml.uedasoft.com
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ja,en;q=0.9,fr;q=0.8,en-US;q=0.7
Connection: Keep-Alive
Origin: http://localhost:8080
Referer: http://localhost:8080/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
X-Forwarded-For: 125.172.88.148
X-Forwarded-Host: ml.uedasoft.com
X-Forwarded-Server: ml.uedasoft.com
runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:199 (0x5595f)
panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:394 (0x55838)
sigpanic: panicmem()
/usr/local/go/src/runtime/internal/atomic/atomic_arm.go:103 (0x126db)
goXadd64: *(*int)(nil) = 0 // crash on unaligned uint64
/home/ueda/.go/src/go.opencensus.io/trace/trace.go:483 (0x50b937)
(*defaultIDGenerator).NewSpanID: id = atomic.AddUint64(&gen.nextSpanID, gen.spanIDInc)
/home/ueda/.go/src/go.opencensus.io/trace/trace.go:196 (0x50a26f)
startSpanInternal: span.spanContext.SpanID = cfg.IDGenerator.NewSpanID()
/home/ueda/.go/src/go.opencensus.io/trace/trace.go:162 (0x50a117)
StartSpan: span := startSpanInternal(name, parent != SpanContext{}, parent, false, opts)
/home/ueda/.go/src/go.opencensus.io/plugin/ochttp/trace.go:58 (0x51713b)
(*traceTransport).RoundTrip: ctx, span := trace.StartSpan(req.Context(), name,
/home/ueda/.go/src/go.opencensus.io/plugin/ochttp/client_stats.go:54 (0x516b1b)
statsTransport.RoundTrip: resp, err := t.base.RoundTrip(req)
/home/ueda/.go/src/go.opencensus.io/plugin/ochttp/client.go:89 (0x5165c7)
(*Transport).RoundTrip: return rt.RoundTrip(req)
/usr/local/go/src/net/http/client.go:250 (0x25ec27)
send: resp, err = rt.RoundTrip(req)
/usr/local/go/src/net/http/client.go:174 (0x25e6ef)
(*Client).send: resp, didTimeout, err = send(req, c.transport(), deadline)
/usr/local/go/src/net/http/client.go:641 (0x25fb17)
(*Client).do: if resp, didTimeout, err = c.send(req, deadline); err != nil {
/usr/local/go/src/net/http/client.go:509 (0x4f9def)
(*Client).Do: return c.do(req)
/home/ueda/.go/src/golang.org/x/net/context/ctxhttp/ctxhttp.go:30 (0x4f9d60)
Do: resp, err := client.Do(req.WithContext(ctx))
/home/ueda/.go/src/firebase.google.com/go/auth/token_verifier.go:92 (0x59750b)
(*httpKeySource).refreshKeys: resp, err := ctxhttp.Do(ctx, k.HTTPClient, req)
/home/ueda/.go/src/firebase.google.com/go/auth/token_verifier.go:72 (0x59733b)
(*httpKeySource).Keys: err := k.refreshKeys(ctx)
/home/ueda/.go/src/firebase.google.com/go/auth/token_verifier.go:129 (0x5979e3)
verifyToken: keys, err := ks.Keys(ctx)
/home/ueda/.go/src/firebase.google.com/go/auth/auth.go:223 (0x59529f)
(*Client).VerifyIDToken: if err := verifyToken(ctx, idToken, c.keySource); err != nil {
/home/ueda/ml/main.go:97 (0x5fdc33)
main.func5: token, err := client.VerifyIDToken(context.Background(), idToken)
/home/ueda/.go/src/github.com/gin-gonic/gin/context.go:147 (0x48710f)
(*Context).Next: c.handlers[c.index](c)
/home/ueda/.go/src/github.com/gin-gonic/gin/recovery.go:83 (0x497efb)
RecoveryWithWriter.func1: c.Next()
/home/ueda/.go/src/github.com/gin-gonic/gin/context.go:147 (0x48710f)
(*Context).Next: c.handlers[c.index](c)
/home/ueda/.go/src/github.com/gin-gonic/gin/logger.go:241 (0x497347)
LoggerWithConfig.func1: c.Next()
/home/ueda/.go/src/github.com/gin-gonic/gin/context.go:147 (0x48710f)
(*Context).Next: c.handlers[c.index](c)
/home/ueda/.go/src/github.com/gin-gonic/gin/gin.go:412 (0x48f8bf)
(*Engine).handleHTTPRequest: c.Next()
/home/ueda/.go/src/github.com/gin-gonic/gin/gin.go:370 (0x48f19f)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2802 (0x2a2c7f)
serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1890 (0x29f12f)
(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_arm.s:868 (0x6c86f)
goexit: MOVW R0, R0 // NOP
[GIN] 2020/03/02 - 13:35:58 | 500 | 13.345389ms | 125.172.88.148 | GET /idToken/eyJhbGciOiJSUzI1NiIsImtpZCI6IjBlYTNmN2EwMjQ4YmU0ZTBkZjAyYWVlZWIyMGIxZDJlMmI3ZjI0NzQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi5LiK55Sw5YGl5LmLIiwiaXNzIjoiaHR0cHM6Ly9zZWN1cmV0b2tlbi5nb29nbGUuY29tL21hZ2ljbGFiZWwtYjQ0NjkiLCJhdWQiOiJtYWdpY2xhYmVsLWI0NDY5IiwiYXV0aF90aW1lIjoxNTgzMTE2MjQwLCJ1c2VyX2lkIjoiS0V5b3dYZnd4NFNqbEMwakdsTnVzcDU0c0xQMiIsInN1YiI6IktFeW93WGZ3eDRTamxDMGpHbE51c3A1NHNMUDIiLCJpYXQiOjE1ODMxMjM3NTcsImV4cCI6MTU4MzEyNzM1NywiZW1haWwiOiJnZGUwMDEwN0BuaWZ0eS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJnZGUwMDEwN0BuaWZ0eS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.ABnMA6iOITghzo_WzgdDwssODiLsswVSlKod6w5CHcnkJOQVKqQIynZufTQvcF8nQO77MYXikZD8TQE_uGq3EpHWQibun67mvN74GnPaguzgvpjQ-PqIOzuhnn2n2SpHSacdREtFkwtj1S66bhigbuTJbqr8jQtIEIB6gfmnObwcmpNRsc-GGR45xjWAO6UY4Ygw4xDcHsHGXwL6SA-HbDuSZGeQfXtdPt94taJfrQQB9nr_7gRjttQLz4ongh-g-fMSpWx3z8lmQgPwgg4GyChYPZ6_hdEV3AWFJTHptE2X8RCV6HfpZB6EGwvLQr6ZrC01uodGTg87BvtPrersjA
I've completely no idea of the cause of this panic. Any suggestions are so welcome! Thank you for your suggestions.
As commented by mkopriva, root cause was a reported issue. It's fixed by updating dependencies as follows:
go get -u all
Thank you, mkopriva!

How to send SMS using Delphi Code

I have made 3 attempts using Indy10.6.2 component, none of which show any errors, but the code is unable to send SMS. Please help me to send me the SMS through Delphi code.
Attempt 1
const
URL = 'https://api.bulksmsgateway.in/send/? username=****&hash=****&sender=TXTLCL&numbers=9198........&message=HISUNDAR';
//URL = 'https://api.textlocal.in/send/? username=*****&hash=******&sender=TXTLCL&numbers=9198...&message=HISUNDAR';
ResponseSize = 1024;
var
hSession, hURL: HInternet;
Request: String;
ResponseLength: Cardinal;
begin
hSession := InternetOpen('TEST', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
Request := Format(URL, [Username,Password,Sender,Numbers,HttpEncode(Message1)]);
hURL := InternetOpenURL(hSession, PChar(Request), nil, 0,0,0);
try
SetLength(Result, ResponseSize);
InternetReadFile(hURL, PChar(Result), ResponseSize, ResponseLength);
SetLength(Result, ResponseLength);
finally
InternetCloseHandle(hURL)
end;
showmessage(result);
finally
InternetCloseHandle(hSession)
end
Attempt 2
var
http : TIdHTTP;
IdSSL : TIdSSLIOHandlerSocketOpenSSL;
begin
http := TIdHTTP.Create(nil);
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try
Http.ReadTimeout := 30000;
Http.IOHandler := IdSSL;
IdSSL.SSLOptions.Method := sslvTLSv1;
Http.Request.BasicAuthentication := True;
// IdSSL.SSLOptions.Method := sslvTLSv1;
//IdSSL.SSLOptions.Method := sslvTLSv1;
// http.Get('https://www.smsgatewayhub.com/api/mt/SendSMS? APIKey=B215dPone0yVIJU2QDH&senderid=TESTIN&channel=2&DCS=0&flashsms=0&number= 9195.....&text=test message&route=1');
http.Get('http://login.bulksmsgateway.in/sendmessage.php? user=****&password=****&mobile=95661....&message=Good Morning&sender=PRAPUS&type=3 ');
finally
http.Free;
end;
Attempt 3
var
lHTTP: TIdHTTP;
lParamList: TStringList;
lResult: String;
IdSSL : TIdSSLIOHandlerSocketOpenSSL;
begin
lParamList := TStringList.Create;
lParamList.Add('username=****');
lParamList.Add('password=****');
lParamList.Add('msgtext=Hello World');
lParamList.Add('originator=TestAccount');
lParamList.Add('phone=+9195....');
lParamList.Add('showDLR=0');
lParamList.Add('charset=0');
lParamList.Add('msgtype=');
lParamList.Add('provider=bulksmsgateway.in');
lHTTP := TIdHTTP.Create(nil);
try
lResult := lHTTP.Post('http://login.bulksmsgateway.in/sendmessage.php?', lParamList);
//WriteLn(lResult);
// Readln;
finally
FreeAndNil(lHTTP);
FreeAndNil(lParamList);
end;
You are sending the wrong parameters to the wrong URLs using the wrong HTTP methods. Per the code examples on the Bulk SMS Gateway website, you need to use HTTP POST with the correct URL and parameters. Please follow the online examples.
Try something more like this instead:
var
lHTTP: TIdHTTP;
lParamList: TStringList;
lResult: String;
IdSSL : TIdSSLIOHandlerSocketOpenSSL;
begin
lParamList := TStringList.Create;
try
lParamList.Add('user=****');
lParamList.Add('password=****' );
lParamList.Add('message=Hello World');
lParamList.Add('sender=TestAccount');
lParamList.Add('mobile=+9195....');
lParamList.Add('type=1'); // or 3
lHTTP := TIdHTTP.Create(nil);
try
// note: if you are using an up-to-date version of Indy,
// assigning the IOHandler is optional:
//
// http://www.indyproject.org/sockets/blogs/ChangeLog/20141222.aspx
//
lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
try
lResult := lHTTP.Post('https://www.bulksmsgateway.in/sendmessage.php', lParamList);
// WriteLn(lResult);
// Readln;
except
on E: Exception do begin
//WriteLn('Error: ', e.Message);
end;
end;
finally
FreeAndNil(lHTTP);
end;
finally
FreeAndNil(lParamList);
end;
end;
If you want to send through the SMS Gateway Hub, you have a choice of using HTTP GET, or XML over HTTP POST:
var
lHTTP: TIdHTTP;
lParamList, lResult: String;
IdSSL : TIdSSLIOHandlerSocketOpenSSL;
begin
lParamList := Format('APIKey=%s&senderid=%s&channel=2&DCS=8&flashsms=0&number=%s&text=%s&route=1',
[
'****',
'TestAccount',
'9195....',
'Hello World'
]
);
lHTTP := TIdHTTP.Create(nil);
try
lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
try
lResult := lHTTP.Get('https://www.smsgatewayhub.com/api/mt/SendSMS?' + lParamList);
// WriteLn(lResult);
// Readln;
except
on E: Exception do begin
//WriteLn('Error: ', e.Message);
end;
end;
finally
FreeAndNil(lHTTP);
end;
end;
var
lHTTP: TIdHTTP;
lParamList: TStringStream;
lResult: String;
IdSSL : TIdSSLIOHandlerSocketOpenSSL;
begin
lParamList := TStringStream.Create(
'<SmsQueue>' +
'<Account>' +
'<User>****</User>' +
'<Password>****</Password>' +
'<SenderId>TestAccount</SenderId>' +
'<Channel>1</Channel>' +
'<DCS>0</DCS>' +
'<FlashSms>0</FlashSms>' +
'<Route>1</Route>' +
'</Account>' +
'<Messages>' +
'<Message>' +
'<Number>9195....</Number>' +
'<Text>Hello World</Text>' +
'</Message>' +
'</Messages>' +
'</SmsQueue>',
TEncoding.UTF8);
try
lHTTP := TIdHTTP.Create(nil);
try
lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
try
lHTTP.Request.ContentType := 'text/xml';
lHTTP.Request.Charset := 'utf-8';
lResult := lHTTP.Post('https://www.smsgatewayhub.com/RestAPI/MT.svc/mt', lParamList);
// WriteLn(lResult);
// Readln;
except
on E: Exception do begin
//WriteLn('Error: ', e.Message);
end;
end;
finally
FreeAndNil(lHTTP);
end;
finally
FreeAndNil(lParams);
end;
end;

how to make http get request using TclientSocket?

I tried the following HTTP GET request
function CreateHTTPRequest(Site: String): String;
var
Request: String;
begin
Randomize;
Request := 'GET ' + Site + ' HTTP/1.1' + #13#10;
Request := Request + 'Host: ' + Site + #13#10;
Request := Request + 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' + #13#10;
Request := Request + 'Accept-Language: en-us,en' + #13#10;
Request := Request + 'User-Agent: ' + UserAgent + #13#10;
Request := Request + 'Referer: ' + Referer + #13#10;
Request := Request + 'Connection: close' + #13#10#13#10;
Result := Request;
end;
var
httpSocket: TClientSocket;
Site: String;
Target : string;
begin
httpSocket := TClientSocket.Create(nil);
httpSocket.Host := 'www.google.com';
httpSocket.Port := 80;
httpSocket.ClientType := ctBlocking;
httpSocket.Active := True;
if httpSocket.Socket.Connected=True then
begin
memo1.Lines.Add('requested');
Site := 'http://' + 'google.com';
httpSocket.Socket.SendText(CreateHTTPRequest(Site));
memo1.Lines.Add(httpSocket.Socket.ReceiveText);
httpSocket.Active := False;
end;
httpSocket.Free;
end;
I don't get any response from this. What did I do wrong? I cannot do any more HTTPS requests with TclientSocket. Is it dead already?

http NewRequest get unexpected characters

I try to parse a page with this code :
client := &http.Client{}
profile := getEpiURL(login)
log.Print("Fetch " + profile)
req, err := http.NewRequest("GET", profile, nil)
if err != nil {
log.Fatal(err)
}
req.AddCookie(cookieSessionIntra)
body, _ := httputil.DumpRequestOut(req, true)
With this as getEpiURL function :
func getEpiURL(login string) (url string) {
url = "https://********/user/" + login + "/?format=json"
return
}
And when i look at the output the profile variable is good, but in the Request it seems obviously wrong...
2016/11/24 12:53:53 Fetch https://********/user/le****in-vi**rd#e*******/?format=json
Then the debug for the request prints me :
GET /user/%00l%*****0o%*00.%00c***0-%00v%00i%0*a%00r%00d%00#%00e%00i%00t%00e%00c%0***0.%0***00/?format=json
HTTP/1.1 Host: ****** User-Agent: Go-http-client/1.1 Cookie:
PHPSESSID=********* Accept-Encoding: gzip
I think your original string somehow contains NUL characters. Try this out in the playground:
func main() {
req, err := http.NewRequest("GET", "https://some/normal/path", nil)
if err != nil {
log.Fatal(err)
}
body, _ := httputil.DumpRequestOut(req, true)
fmt.Printf("Hello, playground, %q", body)
}
You'll get:
"GET /normal/path HTTP/1.1\r\nHost: some...
Now try it with a string in which you inserted NUL characters:
req, err := http.NewRequest("GET", "https://some/\000n\000o\000rmal/path", nil)
...
"GET /%00n%00o%00rmal/path HTTP/1.1\r\nHost: some...
Not quite sure how your string ended up containing those. Read more about percent encoding.

Resources