I want to create a POST request in Fiddler Script (jscript.net) by means of WebClient(), but this is not working.
How can I create POST request in Fiddler Script ?
import System;
import Fiddler;
import System.Text;
import System.Windows.Forms;
import System.Collections;
import System.Collections.Generic;
import System.Collections.Specialized;
import System.Text.RegularExpressions;
import System.Runtime;
import System.Net;
public class Handlers {
static function OnBeforeResponse(oSession: Session) {
if (oSession.HostnameIs("test.com")){
var param = '{"data1":"value1","data2":"value2"}';
var url = "http://test2.com/test.php";
var client = new WebClient();
client.Headers.Add("content-type", "application/json");
var response = Encoding.ASCII.GetString(client.UploadString(url, "POST", Encoding.UTF8.GetBytes(param)));
FiddlerObject.alert(response);
}
}
}
Related
After upgrading from Play! 2.4 to Play! 2.5 there seems to be a problem with form-enconding. German umlauts for example really get messed up. For example the german word "Bär" becomes "Bär".
I already changed the way I access form data from
Form.form(Form.class).bindFromRequest();
to the injected way, as described in the migration guide:
formFactory.form(Form.class).bindFromRequest();
Is there a was to fix the character encoding in Play 2.5?
This is a bug in play 2.5 , see github issue: https://github.com/playframework/playframework/pull/5920
I resolve this with a custom body parser:
package com.kashi.ssff.services;
import akka.util.ByteString;
import play.api.http.HttpConfiguration;
import play.core.parsers.FormUrlEncodedParser;
import play.http.HttpErrorHandler;
import play.libs.F;
import play.libs.streams.Accumulator;
import play.mvc.BodyParser;
import play.mvc.BodyParsers;
import play.mvc.Http;
import play.mvc.Result;
import javax.inject.Inject;
import java.util.Map;
/**
* Created by mohsen on 3/21/16.
*/
public class FormBodyParser extends BodyParser.BufferingBodyParser<Map<String, String[]>> {
private final HttpErrorHandler errorHandler;
public FormBodyParser(long maxLength, HttpErrorHandler errorHandler) {
super(maxLength, errorHandler, "Error parsing form");
this.errorHandler = errorHandler;
}
#Inject
public FormBodyParser(HttpConfiguration httpConfiguration, HttpErrorHandler errorHandler) {
super(httpConfiguration, errorHandler, "Error parsing form");
this.errorHandler = errorHandler;
}
#Override
public Accumulator<ByteString, F.Either<Result, Map<String, String[]>>> apply(Http.RequestHeader request) {
return BodyParsers.validateContentType(errorHandler, request, "Expected application/x-www-form-urlencoded",
ct -> ct.equalsIgnoreCase("application/x-www-form-urlencoded"), super::apply);
}
#Override
protected Map<String, String[]> parse(Http.RequestHeader request, ByteString bytes) throws Exception {
String charset = request.charset().orElse("UTF-8");
return FormUrlEncodedParser.parseAsJavaArrayValues(bytes.decodeString(charset), charset);
}
}
and annotate controller with this body parser:
#BodyParser.Of(FormBodyParser.class)
public Result register() {
.
.
.
With special thanks #GregMethvin
in your form try adding the accept-charset="ISO-8859-1"
<form accept-charset="ISO-8859-1" action="whatever" method="post">
tested it for the word Bär and it works fine
EDIT:
For the arabic script the characters are stored as ISO-8859-1 encoded as well. An image to show that at the end all goes well.
I am using a PCL project.
I need to send a HTTP POST request with some parameters as well as HTTP header to the web service. The web-service will then return json data back to my client.
How should I do that ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public interface IJsonHelper
{
Task<IEnumerable<OverallOutlet>> GetData();
}
public class JsonHelper : IJsonHelper
{
string url = "http://someurl.com";
public async Task<IEnumerable<OverallOutlet>> GetData()
{
var client = new HttpClient();
// How to add http header (for example, Key : token, Value : 123456) ?
var post_data = new FormUrlEncodedContent( new [] {
new KeyValuePair<string, string>("username", ""),
new KeyValuePair<string, string>("password", "")
});
var result = await client.PostAsync(url, post_data);
return JsonConvert.DeserializeObject<IEnumerable<OverallOutlet>>(result.ToString());
}
}
Call client.DefaultRequestHeaders.Add("Key", "value"); in order to set the request header.
EDIT:
Or you create a HttpRequestMessage and add the headers. You can send the message via client.SendAsync. Look here http://massivescale.com/custom-headers-with-httpclient/
I am new to Vaadin.
As in topic I would like to make http get reaquest in order to retieve some JSON data.
How could I do this ?
I have been trying to make this by com.google.gwt.http.client.RequestBuilder, but I have obtained
java.lang.UnsatisfiedLinkError: com.google.gwt.xhr.client.XMLHttpRequest.create().
I think the error is associated to GWT client - side nature.
So how could I make http get request in Vaadin 7 server - side ?
Here is my code:
package com.example.soaclient;
import javax.servlet.annotation.WebServlet;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("soaclient")
public class SoaclientUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = SoaclientUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
layout.addComponent(new Label("Thank you for clicking"));
String url = "some URL goes here";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
}
});
layout.addComponent(button);
}
}
With Vaadin you should not use anything from com.google.gwt.http.client package. That is only for client side development, e.g. when you make components that need client side counterparts.
Instead of GWT classes you should just stick to generic JDK libraries. E.g. you could simply use java.net.URL.openStream(). But if you are consuming some REST services, you could refer to my recent JAX-RS 2.0 Client article.
I am reading IntroToRx and I'm having a bit of trouble with the sample code. Here is the sum total of my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LearningReactiveExtensions
{
public class Program
{
static void Main(string[] args)
{
var observable = Observable.Interval(TimeSpan.FromSeconds(5));
observable.Subscribe(
Console.WriteLine,
() => Console.WriteLine("Completed")
);
Console.WriteLine("Done");
Console.ReadKey();
}
}
}
If I understand the book correctly, this should write a sequence of numbers to the console, once every five seconds forever since I never Dispose() of the sequence.
However, when I run the code, all I get is the "Done" at the end. No numbers, no "completed", nothing but "Done".
What am I doing wrong here?
I am assuming you haven't had the patience to wait for 5 seconds to elapse otherwise you would have seen that the code is working.
The main idea to keep in mind with Rx is that Observable.Subscribe will return control to calling method almost immediately. In other words, Observable.Subscribe does not block until the results are produced. Thus the call to Console.WriteLine will be invoked only after five seconds.
You need some way to make the main thread wait for what you are doing. You can use a semaphore if you like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LearningReactiveExtensions
{
public class Program
{
static void Main(string[] args)
{
SemaphoreSlim ss = new SemaphoreSlim(1);
var observable = Observable.Interval(TimeSpan.FromSeconds(5));
observable.Subscribe(
Console.WriteLine,
() => {
Console.WriteLine("Completed");
ss.Release();
}
);
ss.Wait();
Console.WriteLine("Done");
Console.ReadKey();
}
}
}
Though probably better in this case just to write
static void Main(string[] args)
{
SemaphoreSlim ss = new SemaphoreSlim(1);
Observable.Interval(TimeSpan.FromSeconds(5)).Wait();
Console.WriteLine("Completed");
Console.WriteLine("Done");
Console.ReadKey();
}
my code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
import clients.NewJerseyClient;
import entities.ReservationItem;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.ws.rs.core.GenericType;
import parameters.ReservationParam;
import org.glassfish.jersey.client.ClientResponse;
/**
*
* #author subhi2
*/
#ManagedBean
#SessionScoped
public class PageController implements Serializable {
public String moveToPage2() {
NewJerseyClient client = new NewJerseyClient();
ClientResponse response = client.findInsertedReservationItem(ClientResponse.class, "22", "2010-07-26T11:15:51", "2014-07-26T11:15:51");
GenericType<List<ReservationItem>> genericType = new GenericType<List<ReservationItem>>() {
};
// Returns an ArrayList of Players from the web service
List<ReservationItem> data = new ArrayList<ReservationItem>();
data = (response.getEntity(genericType));
return data.toString();
}
}
the line
data = (response.getEntity(genericType));
cause the error
this code was working with old jersey but now what should I do to solve this error ?
You can change response.getEntity(genericType) by response.readEntity(genericType)
For what you are asking I've replaced this
response.getEntity(String.class);
by this
response.getEntityStream().toString();
But there could be another problems related with Jersey 2, I could get it working by replacing these imports
import jersey.spi.container.servlet.ServletContainer;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
By these
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.client.ClientResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
and in the code (as I was using Jetty) I had to replace this
servletHolder.setInitParameter("com.sun.jersey.config.property.packages",
"resources");
by this
servletHolder.setInitParameter("jersey.config.server.provider.packages",
"resources");
and this
WebResource webResource = client.resource("http://url_u_want_to_connect");
ClientResponse response = webResource.accept("application/json")
by this
WebTarget webTarget = client.target("http://url_u_want_to_connect");
ClientResponse response = webTarget.request("application/json")
Finally here is a link for "latest" docs (It's about Jersey 2.x, at 2013)
https://jersey.java.net/documentation/latest/user-guide.html