I've never been good in httpWebRequest. Always preferred WebClient but... desperate time, desperate measures.
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
//allDone.Set();
}
catch (WebException exception)
{
}
}
I can see (when I put breakpoint next) that responseString is beautiul JSON but I can't print it out (MessageBox etc) as my app will break.
Could you tell me how to handle that?
Cheers
Added magic
Dispatcher.BeginInvoke(() => { MessageBox.Show("OK"); });
And worked like a charm :)
Try this one
using System.Net;
public void sendRequest()
{
WebRequest webRequest;
webRequest = WebRequest.Create(XXXXXXXXXX);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(newAsyncCallback(GetRequestStreamCallback), webRequest);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "Test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
}
else
{
//Your response will be available in "Response"
}
}
catch (WebException)
{
//error
}
}
here the XXXXXXXX means your url with data which is sent to the server.
Related
Using JAVA, I am trying to republish a dashboard to a particular User. It returns me HTTP status 500. Below is the code for it.
String sisenseURL = surl; // This is correct URL to POST API for PUBLISH
String urlParameters = "force=true";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
URL url = new URL( sisenseURL );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setRequestProperty("Authorization", accessToken);
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write( postData );
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
stringBuffer.append(line);
}
in.close();
The request runs file with POSTMAN as well as with the Swagger UI for Sisense.
Any help would be greatly appreciated.
TIA
Ashutosh
Here is a java example for sisense V6.7 of updating dashboard shares using the rest API
You didnt share your payload so not sure if thats the problem, but the example below worked for me.
I took the sendPostRequest code from here
import java.io.*;
import java.net.*;
public class Runner {
public static void main(String[] args){
try {
//Dashboard shares payload
String payload = "{\"sharesTo\":[{\"shareId\":\"58504c5221785b627cb4361d\",\"type\":\"user\",\"subscribe\":false},{\"shareId\":\"58505ba6ec4df9701a000019\",\"type\":\"user\",\"rule\":\"view\",\"subscribe\":false}]}";
String str = sendPostRequest(getDashboardUrl(), payload);
System.out.println("Done");
}
catch (RuntimeException e){
}
}
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Authorization", getAuthorization());
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public static String getDashboardUrl(){
//Sisense domain
String baseURL = "http://localhost:8081";
return baseURL + "/api/shares/dashboard/5850511cec4df9701a000013";
}
public static String getAuthorization(){
return "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiNTg1MDRjNTIyMTc4NWI2MjdjYjQzNjFkIiwiYXBpU2VjcmV0IjoiOGUwZDIyOWItY2VmMS0xYTE4LTNhYWEtYmY1ZmE1ZmNkNTExIiwiaWF0IjoxNTE1MDEzMzkxfQ.zgx0Nv8YztfM2rm5WTCnJ0R6C_n5V-HNkEZgAcINfs4";
}
}
I'm using Apache HTTPClient 4.5.3 to make some HTTP requests, but I am getting a g-zipped response I have tried many things I found online but non of them worked. I still get gibberish when I print the response. Below are the relevant code. What do I need to do to get a human readable response?
static public CloseableHttpClient CreateHttpClient() {
// return
// HttpClients.custom().disableAutomaticRetries().setHttpProcessor(HttpProcessorBuilder.create().build())
// .build();
return HttpClientBuilder.create().disableAutomaticRetries()
.setHttpProcessor(HttpProcessorBuilder.create().build()).build();
}
static public RequestConfig GetConfig() {
return RequestConfig.custom().setSocketTimeout(READTIMEOUT).setConnectTimeout(CONNECTTIMEOUT)
.setConnectionRequestTimeout(REQUESTTIMEOUT).build();
}
static public String updates() {
String result = "";
String url = "https://example.com";
CloseableHttpClient httpClient = CreateHttpClient();
CloseableHttpResponse response = null;
URL urlObj;
RequestConfig config = GetConfig();
try {
urlObj = new URL(url);
HttpPost request = new HttpPost(url);
request.setConfig(config);
StringEntity params = new StringEntity("example");
request.addHeader("Accept-Language", "en");
request.addHeader("Content-Type", "application/json; charset=UTF-8");
request.addHeader("Content-Length", String.valueOf(params.getContentLength()));
request.addHeader("Host", urlObj.getHost());
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Accept-Encoding", "gzip");
request.setEntity(params);
response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("updates response code: " + responseCode);
// BufferedReader rd = new BufferedReader(new
// InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = EntityUtils.toString(response.getEntity());
// String line = "";
// while ((line = rd.readLine()) != null) {
// result.append(line);
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You should get the content from the response entity which is an InputStream. Than you could create a String from that InputStream with BufferedReader
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertInputStreamToString(instream);
instream.close();
}
Write your own convertInputStreamToString. If you need help for doing that check here:
Read/convert an InputStream to a String
I'm trying login to website(example: https://www.facebook.com/login.php?login_attempt=1) using httpwebrequest by POST. But It's not return result after login.
I don't know what is wrong with my code, can you help me? Thanks so much!
This is my code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("https://www.facebook.com/login.php?login_attempt=1");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
StringBuilder postData = new StringBuilder();
postData.Append("email=myEmail");
postData.Append("&password=myPassword");
byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// something do
});
}
}
I had just a quick look: https://www.facebook.com/login.php 's input fields are named "email" and "pass" (not "password").
Untested: Change
postData.Append("&password=myPassword");
to
postData.Append("&pass=myPassword");
Even if this works, I doubt that you get much further with whatever you intend to do. I recommend using one of the Facebook SDKs.
I have create a jSON web service to save profile data with image. my service work properly but when send data to service HttpWebRequest return "The remote server returned an error: NotFound."
My code is this
void SendPost()
{
string webServiceAddress = #"http://localhost:51018/AMFDecember/WebService.asmx";
string methodName = "Register";
string url = string.Format("{0}/{1}", webServiceAddress, methodName);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackx), webRequest);
}
void GetRequestStreamCallbackx(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
StreamReader streamReader = new StreamReader(postStream);
string Response = streamReader.ReadToEnd();
string img="";
try
{
string img = Convert.ToBase64String(imageBytes);
}
catch { }
// Create the post data
string postData = "";
// <emailID>string</emailID>
//<pwd>string</pwd>
//<name>string</name>
//<img>base64Binary</img>
postData = "emailID=pr#pr.pr&pwd=1234&name=test&img=" + Convert.ToBase64String(imageBytes) + "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
try
{
postStream.Write(byteArray, 0, byteArray.Length);
}
catch { }
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
I think your problem might be "http://localhost" - this means the service should be on localhost - i.e. within your phone?
Maybe try using the network ip address of your PC instead - you might need to use full IIS or IISExpress to host your service for this.
i have this
{"invoices":{"POSWorkstationID":"POS7","POSClerkID":"admin","CustomerName":"Alice in Wonderland Tours","IsFreightOverwrite":true},"invoiceDetails":[{"ItemDescription":"Old World Lamppost","QuantityOrdered":"1","SalePriceRate":" $107.99","ExtPriceRate":"107.99","ItemType":"Stock","LineNum":1,"WarehouseCode":"Main"}]}
Now i want to pass this on my server using rest and convert it to stream. My service code is here. https://stackoverflow.com/questions/9594382/convert-json-to-stream-in-wcf
Please find some sample code to get your scenario working:
On my Server:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string CreateInvoice(Stream xmlStream)
{
byte[] buffer = new byte[WebOperationContext.Current.IncomingRequest.ContentLength];
int read = -1;
while (read != 0)
{
read = xmlStream.Read(buffer, 0, buffer.Length);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string jsonobjectstring = enc.GetString(buffer);
JavaScriptSerializer json = new JavaScriptSerializer();
object jsonobject = json.DeserializeObject(jsonobjectstring);
return "Recieved the json text on server";
//MaintainInvoice(xmlStream, InvoiceMaintainance.CreateInvoice);
}
I have modified the server method logic so that i can test it. Once you get the stream on the server you can use your logic to return the invoice object as needed.
Now on client side to invoke the rest service i use the below code:
private string UseHttpWebApproachByteArray(string serviceUrl, string resourceUrl, string method, byte[] requestBody)
{
string responseMessage = null;
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/octet-stream";
request.Method = method;
}
if (method == "POST" && requestBody != null)
{
request.ContentLength = requestBody.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBody, 0, requestBody.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
return responseMessage;
}
private void Test()
{
string jsonText = "{\"invoices\":{\"POSWorkstationID\":\"POS7\",\"POSClerkID\":\"admin\",\"CustomerName\":\"Alice in Wonderland Tours\",\"IsFreightOverwrite\":true},\"invoiceDetails\":[{\"ItemDescription\":\"Old World Lamppost\",\"QuantityOrdered\":\"1\",\"SalePriceRate\":\" $107.99\",\"ExtPriceRate\":\"107.99\",\"ItemType\":\"Stock\",\"LineNum\":1,\"WarehouseCode\":\"Main\"}]}";
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] jsonBytes = enc.GetBytes(jsonText);
UseHttpWebApproachByteArray(serviceBaseUrl, resourceUrl, method, jsonBytes);
}