vb.net woocommerce api authentication - wordpress

I'm trying to connect to wordpress' woocommerce.com rest api.
I managed to get everything to work with postman but can't seem to get it to work with visual basic this is the code I have so far:
Public Class OAuth1
Shared oauth_consumer_key As String = "blah"
Shared oauth_consumer_Secret As String = "Blah"
Shared Sub wooproductcreate(ByVal json)
Dim token = Form1.TextBox1.Text
Dim resource_url As String = "http://store.example.com/wp-json/wc/v2/products"
Dim oauth_version As String = "1.0"
Dim oauth_signature_method As String = "HMAC-SHA256"
Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim oauth_signature As String = GeneraOAuthSignature(resource_url, _
oauth_nonce, _
oauth_signature_method, _
oauth_timestamp, _
oauth_version)
Dim headerFormat As String = "OAuth oauth_consumer_key=""{0}"",oauth_signature_method=""{1}"",oauth_timestamp=""{2}"",oauth_nonce=""{3}"",oauth_version=""{4}"",oauth_signature=""{5}"""
Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_version), Uri.EscapeDataString(oauth_signature))
ServicePointManager.Expect100Continue = False
Dim req As WebRequest
Dim res As HttpWebResponse
Dim streamReader As StreamReader
Dim contenidoRespuesta As String = ""
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim bytee = Encoding.UTF8.GetBytes(json)
req = WebRequest.Create(resource_url)
req.Timeout = -1
req.Headers.Add("Authorization", authHeader)
req.ContentType = "application/json"
req.Method = "POST"
req.ContentLength = bytee.Length
Dim stream = req.GetRequestStream()
stream.Write(bytee, 0, bytee.Length)
stream.Close()
res = DirectCast(req.GetResponse(), HttpWebResponse)
streamReader = New StreamReader(res.GetResponseStream(), encode)
While True
contenidoRespuesta = streamReader.ReadLine()
End While
'==========================
'CIERRE DE STREAMS Y COMUNICACIONES
'Abort is needed or streamReader.Close() will hang
req.Abort()
streamReader.Close()
streamReader = Nothing
res.Close()
res = Nothing
End Sub
Shared Function GeneraOAuthSignature(ByVal stream_url As String, _
ByVal oauth_nonce As String, _
ByVal oauth_signature_method As String, _
ByVal oauth_timestamp As String, _
ByVal oauth_version As String) As String
Dim baseFormat = "oauth_consumer_key={0}&oauth_signature_method={1}&oauth_timestamp={2}" & _
"&oauth_nonce={3}&oauth_version={4}"
Dim baseString As String = String.Format(baseFormat, _
oauth_consumer_key, _
oauth_signature_method, _
oauth_timestamp, _
oauth_nonce, _
oauth_version)
baseString = String.Concat("POST&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
'Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.
Dim compositeKey As String = String.Concat(Uri.EscapeDataString(oauth_consumer_Secret))
Dim oauth_signature As String
Dim hasher As HMACSHA256 = New HMACSHA256(ASCIIEncoding.ASCII.GetBytes(compositeKey))
Using hasher
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Return oauth_signature
End Function
End Class
The problem is that I get the response "The remote server returned an error: (401) Unauthorized."
I'm not sure what I need to do to over come this problem.
I'm thinking it has to be how the signature is generated maybe it spitting out a invalid signature...
Wireshark outputs this from the code:
POST /wp-json/wc/v2/products HTTP/1.1
Authorization: OAuth oauth_consumer_key="key",oauth_signature_method="HMAC-SHA256",oauth_timestamp="1506468745",oauth_nonce="NjM2NDIwNTExNDUxOTkyMjEy",oauth_version="1.0",oauth_signature="sig"
Content-Type: application/json
Host: example.com
Content-Length: 890
Connection: Keep-Alive
{
"name": "Premium Quality",
"type": "simple",
"regular_price": "21.99",
"description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
"short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
"categories": [
{
"id": 9
},
{
"id": 14
}
],
"images": [
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg",
"position": 0
},
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg",
"position": 1
}
]
}HTTP/1.1 401 Unauthorized
Date: Tue, 26 Sep 2017 23:32:24 GMT
Server: Apache
X-Powered-By: PHP/5.5.38
X-Robots-Tag: noindex
Link: <http://example.com/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Access-Control-Allow-Headers: Authorization, Content-Type
Vary: Accept-Encoding,User-Agent
Keep-Alive: timeout=5
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
89
{"code":"woocommerce_rest_authentication_error","message":"Invalid signature - provided signature does not match.","data":{"status":401}}
0
When I use the postman I get a response that works and creates the product with no problem
POST /wp-json/wc/v2/products HTTP/1.1
Host: example.com
Connection: keep-alive
Content-Length: 890
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Content-Type: application/json
Authorization: OAuth oauth_consumer_key="key",oauth_signature_method="HMAC-SHA256",oauth_timestamp="1506468730",oauth_nonce="HJVzFL",oauth_version="1.0",oauth_signature="sig"
Postman-Token: 95240347-868c-03d0-55a9-d2fb7c51b8e2
Accept: */*
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: woocommerce_items_in_cart=1; woocommerce_cart_hash=some hash; wp_woocommerce_session_d0d4322f0d3b54c7984c1c37276328=somenumbers
{
"name": "Premium Quality",
"type": "simple",
"regular_price": "21.99",
"description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
"short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
"categories": [
{
"id": 9
},
{
"id": 14
}
],
"images": [
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg",
"position": 0
},
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg",
"position": 1
}
]
}HTTP/1.1 201 Created
Date: Tue, 26 Sep 2017 23:32:09 GMT
Server: Apache
X-Powered-By: PHP/5.5.38
X-Robots-Tag: noindex
Link: <http://example.com/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Access-Control-Allow-Headers: Authorization, Content-Type
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Allow: GET, POST
Access-Control-Allow-Origin:
Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Credentials: true
Vary: Origin,Accept-Encoding,User-Agent
Set-Cookie: woocommerce_items_in_cart=1; path=/
Set-Cookie: woocommerce_cart_hash=some hash; path=/
Set-Cookie: wp_woocommerce_session_d0d4322f0d3b545798c1cb7276328=some hash; expires=Thu, 28-Sep-2017 16:25:49 GMT; Max-Age=147217; path=/
Location: http://example.com/wp-json/wc/v2/products/1066
Content-Encoding: gzip
Content-Length: 1041
Keep-Alive: timeout=5
Connection: Keep-Alive
Content-Type: application/json; charset=UTF-8
...........V.n#7...a
........
P...Rt..u1.5.X.....#...hn..i.....X").:.!...u.^.WW..pM.....e.......bR...(\...u..%T.....B....7..<D.i.....IG!/)... .7s.m.D..g.7s..y.Jx..r+....i....>.V...z.|fT5:>5\^<5...;.....U...2JAj.(..yL!...J.=D;d.|...*...<re.. .....u.nZ.5.......?...R.L.p....VFn"..o%.^.(.".!..."3./.....9..9...!.'.l.......r.........z.v...#; .MXR.%$.'..E...AF... '...,.`...[.v..N...U.Tf.W....o-.x.v3.;O..s...H......)...(.......w...v..6!^.~.!..r1[....$.}.\..|...fM..w..bm.R/(.J|A.....O.!.}.*..........8Z.*j...7.l..M&?]....o...=.q....V....]\..........W.......{.x&.:..Q. Ik.6....G...Hm.FY<.... ..O...VJj ...3..;.O...#y.x...Q.)Fd......W#....Y..E......`h...U..#..[.w.!.`.]x....5.....\Rq.......3Y......A.#J.F..d...QKM&.$..P. M.w.....~<...%....<.%.F.2......g.<.Uy...".I...u...t...<..A9+...v_.\..y.v|9.xr......".S....8....U.......X/.?.y...FZy.0...^.P...(.;..7....V...^|.0>...h. .<..K.y.......c.........g...w.V\.5.,.~........;.Z............=T...Dj...... .g...v...z.?p....8..o....O.^
.....m.c
.
h.N[.... .......v_...`
.b3?,.O9...!.|%a1.Ew.o.........[..
..
I've tried a few different things and have improved the code. However I still can't seem to get the signature to generate correctly it's always saying it doesn't match.
Imports RestSharp Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Shared oauth_consumer_key As String = "ck_xxx"
Shared oauth_consumer_Secret As String = "cs_XXX"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim resource_url As String = "http://example.com/wp-json/wc/v2/products"
Dim oauth_signature_method As String = "HMAC-SHA256"
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim oauth_version As String = "1.0"
Dim oauth_signature As String = GeneraOAuthSignature(resource_url, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version)
Dim auth As String = "oauth_consumer_key=""" & oauth_consumer_key & """,oauth_signature_method=""" & oauth_signature_method & """,oauth_timestamp=""" & oauth_timestamp & """,oauth_nonce=""" & oauth_nonce & """,oauth_version=""" & oauth_version & """,oauth_signature=""" & oauth_signature & """"
MsgBox(auth)
Dim client = New RestClient(resource_url)
Dim request = New RestRequest(Method.POST)
request.AddHeader("cache-control", "no-cache")
request.AddHeader("content-type", "application/json")
request.AddHeader("authorization", "OAuth " & auth)
request.AddParameter("application/json", TextBox1.Text, ParameterType.RequestBody)
Dim response As IRestResponse = client.Execute(request)
MsgBox(response.Content)
End Sub
Shared Function GeneraOAuthSignature(ByVal stream_url As String, ByVal oauth_nonce As String, ByVal oauth_signature_method As String, ByVal oauth_timestamp As String, ByVal oauth_version As String) As String
'The next step is to generate an encrypted oAuth signature which will be use to validate the request.
'To do this, all of the request data is concatenated into a particular format as follows
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_version={4}"
Dim baseString As String = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version)
baseString = String.Concat("POST&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
MsgBox(baseString)
Dim compositeKey As String = Uri.EscapeDataString(oauth_consumer_Secret)
'Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.
Dim oauth_signature As String
Dim hasher As HMACSHA256 = New HMACSHA256(ASCIIEncoding.ASCII.GetBytes(compositeKey))
Using hasher
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Return oauth_signature
End Function
End Class

You don't need all that code that you wrote, it's easier than you think.
Read the Usage section at the XiaoFaye/WooCommerce.NET github repo.
Also, you can install the WooCommerceNet from the NuGets:
VS > Tools > NuGet Package Manager > Manage NuGet

Related

VB .Net: Json not returning using ASHX

I'm having an issue with my code not returning Json response. I've never built an API using ASHX before. I have checked my Json string being created and it appears to be good.
The returned serialized json looks like this:
"{""Error"":""Error: Import: Unknown SKU Received!""}"
This is the correct message that should be returned. Instead I get Bad Request as a response. Not generating any errors on my code side.
Code Snippet:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim oImporter As Importer
Dim oResponse As Domain.Structures.Structures.ReturnResponse
Dim Input_sr As StreamReader
Dim sData As String
Dim bolError As Boolean = False
Dim obj As New Domain.Models.Order.Order
Dim sError As New order_response_error
Dim sResponse As New order_response_success
Try
Input_sr = New StreamReader(context.Request.InputStream)
sData = Input_sr.ReadToEnd
Input_sr.Close()
If context.Request.ContentType.StartsWith("application/json") Then
obj = JsonConvert.DeserializeObject(Of Domain.Models.Order.Order)(sData)
If obj.api_key = ConfigurationManager.AppSettings("api_key") Then
oImporter = New Importer(sData)
oResponse = oImporter.ImportOrder
context.Response.StatusCode = HttpStatusCode.OK
If oResponse.ReturnCode = "Error" Then
bolError = True
context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = oResponse.ReturnCode + ": " + oResponse.Message
'sError.Error = String.Format(oResponse.ReturnCode, oResponse.Message)
Else
context.Response.StatusCode = HttpStatusCode.OK
sResponse.vendor_order_id = oResponse.Message
End If
Else
bolError = True
context.Response.StatusCode = HttpStatusCode.Unauthorized
sError.Error = "Error: Access Denied"
'sError.Error = String.Format("Error", "Access Denied")
End If
Else
bolError = True
context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = "Error: Invalid content type"
'sError.Error = String.Format("Error", "Invalid content type")
End If
Catch ex As Exception
bolError = True
context.Response.StatusCode = HttpStatusCode.BadRequest
Utils.ErrorEmail("Order Error!", ex, AttachmentName:="Order.xml", AttachmentData:=sData)
sError.Error = String.Format("Error", ex.Message)
End Try
context.Response.ContentType = "application/json"
If bolError Then
context.Response.Write(JsonConvert.SerializeObject(sError))
Else
context.Response.Write(JsonConvert.SerializeObject(sResponse))
End If
End Sub
Error Response from client:
Error:
Cache-Control:
private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?XFxhd2FyZGdyYXBoaWNzLmNvbVxkYXRhXFVzZXJzXG1ob2xtZXNcRGVza3RvcFxDb2xsYWdlXENvbGxhZ2VcQ29sbGFnZS5XZWIuUG9ydGFsXGFwaVx0ZXN0b3JkZXIxLmFzaHg=?=
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods:
GET, POST, OPTIONS
Access-Control-Allow-Headers: X-Requested-With,Content-Type
Date:
Mon, 14 Oct 2019 14:47:57 GMT
Content-Length: 48 bytes
COMPLETE REQUEST HEADERS
pretty
Sec-Fetch-Mode: cors
Origin: chrome-extension://aejoelaoggembcahagimdiliamlcdmfm
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
Content-Type: application/json
Accept: /
Sec-Fetch-Site: cross-site
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: AspxAutoDetectCookieSupport=1
You only have one place in your code where you return a custom message from the server, and with a 'BadRequest', on these lines:
context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = oResponse.ReturnCode + ": " + oResponse.Message
That means your business logic is returning this (I can't say appropriately or not). You need to trace through the business logic to find the logic that is presenting the bad SKU message. From that point of view, the ASHX looks to be working correctly.

how to add data in tableView(Javafx) without binding to column [duplicate]

In java fxml I am retrieving the data from .csv file. I am adding dynamic columns and rows to table view and columns are adding to it but not the rows.
I am trying and searching internet but I could not get any suitable result.
My code:-
public class FXMLDocumentController {
#FXML
private TableView tableView;
String headers[] = null;
String items[] = null;
Employee ee;
#FXML
private void initialize() {
Insert();
}
public void Insert() {
List<String> columns = new ArrayList<String>();
List<String> rows = new ArrayList<String>();
ObservableList<ObservableList> csvData = FXCollections.observableArrayList();
try {
int columnIndex = 0;
TableColumn[] tableColumns;
File f = new File("C:\\Users\\admin\\Desktop\\Project\\shipforecast\\Data\\Recieve\\ShipId-1432530905282-1.csv");
if (f.exists() && !f.isDirectory()) {
FileReader fin = new FileReader(f);
BufferedReader in = new BufferedReader(fin);
String l;
int i = 0;
while ((l = in.readLine()) != null) {
if (i < 1) {
headers = l.split(",");
for (String w : headers) {
columns.add(w);
}
tableColumns = new TableColumn[columns.size()];
columnIndex = 0;
for (String columName : columns) {
//System.out.println("dynamic.FXMLDocumentController.Insert()"+columns.size());
tableColumns[columnIndex++] = new TableColumn(columName);
}
tableView.getColumns().addAll(tableColumns);
} else {
ObservableList<String> row = FXCollections.observableArrayList();
items = l.split(",");
for (String item:items) {
row.add(item);
}
csvData.add(row);
System.out.println("hi");
}
i++;
tableView.getItems().add(csvData);
}
} else {
System.out.println("File Not Found");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
What you are missing is a cellValueFactory for your columns that will tell the column what value to display in its cells.
Something like this:
TableView<ObservableList<String>> tableView = new TableView<>();
List<String> columnNames = dataGenerator.getNext(N_COLS);
for (int i = 0; i < columnNames.size(); i++) {
final int finalIdx = i;
TableColumn<ObservableList<String>, String> column = new TableColumn<>(
columnNames.get(i)
);
column.setCellValueFactory(param ->
new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx))
);
tableView.getColumns().add(column);
}
Sample Application
This solution was based slightly on Narayan's blog post: Updated: Dynamic TableView Data From Database. Rather than that blog post, this solution uses a test data generator to generate some dummy data and some of the Java 8 lambda features which make the cell value factory definition a bit less unwieldy to write and look at.
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import java.util.*;
public class DynamicTableView extends Application {
private static final int N_COLS = 5;
private static final int N_ROWS = 1_000;
public void start(Stage stage) throws Exception {
TestDataGenerator dataGenerator = new TestDataGenerator();
TableView<ObservableList<String>> tableView = new TableView<>();
// add columns
List<String> columnNames = dataGenerator.getNext(N_COLS);
for (int i = 0; i < columnNames.size(); i++) {
final int finalIdx = i;
TableColumn<ObservableList<String>, String> column = new TableColumn<>(
columnNames.get(i)
);
column.setCellValueFactory(param ->
new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx))
);
tableView.getColumns().add(column);
}
// add data
for (int i = 0; i < N_ROWS; i++) {
tableView.getItems().add(
FXCollections.observableArrayList(
dataGenerator.getNext(N_COLS)
)
);
}
tableView.setPrefHeight(200);
Scene scene = new Scene(tableView);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
private static class TestDataGenerator {
private static final String[] LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempus cursus diam ac blandit. Ut ultrices lacus et mattis laoreet. Morbi vehicula tincidunt eros lobortis varius. Nam quis tortor commodo, vehicula ante vitae, sagittis enim. Vivamus mollis placerat leo non pellentesque. Nam blandit, odio quis facilisis posuere, mauris elit tincidunt ante, ut eleifend augue neque dictum diam. Curabitur sed lacus eget dolor laoreet cursus ut cursus elit. Phasellus quis interdum lorem, eget efficitur enim. Curabitur commodo, est ut scelerisque aliquet, urna velit tincidunt massa, tristique varius mi neque et velit. In condimentum quis nisi et ultricies. Nunc posuere felis a velit dictum suscipit ac non nisl. Pellentesque eleifend, purus vel consequat facilisis, sapien lacus rutrum eros, quis finibus lacus magna eget est. Nullam eros nisl, sodales et luctus at, lobortis at sem.".split(" ");
private int curWord = 0;
List<String> getNext(int nWords) {
List<String> words = new ArrayList<>();
for (int i = 0; i < nWords; i++) {
if (curWord == Integer.MAX_VALUE) {
curWord = 0;
}
words.add(LOREM[curWord % LOREM.length]);
curWord++;
}
return words;
}
}
}

Capturing 401 errors with Fiddler - Twitter OAUTH 1.0

I'm trying to view the HTTP request being sent/received to twitter. I tried downloading fiddler4 but it's not registering the 401 error and I'm only receiving the 500 page error. Any ideas on how to view the request being sent so I can trouble shoot the reason?
I tried viewing the site as localhost, 127.0.0.1, and machinename.
Dim oAuthRequest As New Dictionary(Of String, String)
oAuthRequest.Add("resource_url", "https://api.twitter.com/oauth/request_token")
oAuthRequest.Add("oauth_callback", Server.UrlEncode("https://www.site.com/callback/"))
oAuthRequest.Add("oauth_consumer_key", "xxxxxxxx")
oAuthRequest.Add("oauth_nonce", Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())))
oAuthRequest.Add("oauth_signature_method", "HMAC-SHA1")
oAuthRequest.Add("oauth_timestamp", CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString)
oAuthRequest.Add("oauth_token", "authorization_code")
Dim baseFormat As String = "oauth_callback=""{0}""&oauth_consumer_key=""{1}""&oauth_nonce=""{2}""&oauth_signature_method=""HMAC-SHA1""&oauth_timestamp=""{3}""&oauth_version=""" & Uri.EscapeDataString("1.0") & """"
Dim baseString As String = String.Format(baseFormat,
oAuthRequest("oauth_callback"),
oAuthRequest("oauth_consumer_key"),
oAuthRequest("oauth_nonce"),
oAuthRequest("oauth_timestamp"))
baseString = String.Concat("POST&", Uri.EscapeDataString(oAuthRequest("resource_url")), "&", Uri.EscapeDataString(baseString))
oAuthRequest.Add("oauth_signature", SHA1Base64Hash("xxxxxxx&", baseString))
Dim authHeaderFormat As String = "OAuth oauth_callback=""{0}"",oauth_consumer_key=""{1}"",oauth_nonce=""{2}"",oauth_signature=""{3}"",oauth_signature_method=""HMAC-SHA1"",oauth_timestamp=""{4}"",oauth_version=""1.0"""
Dim authHeader As String = String.Format(authHeaderFormat,
Uri.EscapeDataString(oAuthRequest("oauth_callback")),
Uri.EscapeDataString(oAuthRequest("oauth_consumer_key")),
Uri.EscapeDataString(oAuthRequest("oauth_nonce")),
Uri.EscapeDataString(oAuthRequest("oauth_signature")),
Uri.EscapeDataString(oAuthRequest("oauth_timestamp")))
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = CType(WebRequest.Create(oAuthRequest("resource_url")), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Try
Dim response As WebResponse = request.GetResponse()
Catch ex As Exception
Text.text = ex.Message
End Try
If Fiddler shows you a HTTP/500 rather than a HTTP/401, that's because the server is returning HTTP/500. Unless you tell it to do so, Fiddler does not invent responses.

401 unauthorised error when using WebRequest

Am trying to create a simple page that connects to an external website, logs in, and then passes a bunch of parameters.
When I run the page I get a bad request 400 error and when I check using Fiddler I can see there are both 401 and 400 errors being returned. Under 'Auth' in Fiddler I see:
"No Proxy-Authorization Header is present.
No Authorization Header is present." < Is this relevant? As when I test using PHP cUrl the page can log in fine and Fiddler says the same under Auth.
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim testcapture As String = requestStream.ToString
Dim thing As String = "stop"
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
Seems the login credentials are not being passed what am I doing wrong? I am obviously using vb in an asp.net application but am connecting to an XML file held on Linux Apache, does this have any implications at all?
Fiddler appears to be doing strange things for me now so if anyone else can see anything using Fiddler a link to the test file is here:
http://www.filemanage.co.uk/Pubs/Default.aspx

Using ASP.net to pass parameters to external website

I am trying to access a page where I need to log into the website and pass a a list of parameters. I appear to be able to log into the site (if I change the log in details I get a 401 unauthorised error) but then I get a 400 bad request error. The code is a bit hashed together so I know something is wrong but don't know where.
EDITED CODE
Public Sub TestConn()
Dim customeremailaddress As String = HttpUtility.UrlEncode("r.test#test.com")
Dim customername As String = HttpUtility.UrlEncode("Ryan")
Dim referenceid As String = HttpUtility.UrlEncode("ordertest123")
Dim languagecode As String = HttpUtility.UrlEncode("1043")
Dim expirydays As String = HttpUtility.UrlEncode("30")
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
End Sub
You need to send the bytes of the postString not the string itself:
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
...
webRequest__1.ContentLength = postBytes.Length
...
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
More information here.

Resources