[VB.Net] Bild senden in Httpwebrequest (decaptcher.org)

09/23/2013 16:02 maxasoft#1
Hey,

ich bin gerade dabei decaptcher.org in mein Programm einzubauen, die Request (Multipart) die ich nachbauen will sieht wie folgt aus:


Das hatte ich wie folgt versucht:


Aber anstatt des gewünschten Captchacodes erhielt ich nur den Quelltext der API-Seite.

Meine Vermutung: Vielleicht übergebe ich das Bild falsch?

Bisher habe ich es mit folgendem Code in meine Request eingefügt:

PHP Code:
piccode My.Computer.FileSystem.ReadAllText(filename
Ist es evtl. falsch formatiert/codiert?

Würde mich über schnelle Hilfe freuen.

MfG,

maxasoft
09/23/2013 16:19 tolio#2
bytes und nicht text auslesen

System.IO.File.ReadAllBytes
und nachher den kompletten post als utf8
System.Text.Encoding.UTF8.GetBytes
09/23/2013 17:12 maxasoft#3
Ich hab es damit probiert:

PHP Code:
Dim picID() As Byte

       picID 
My.Computer.FileSystem.ReadAllBytes(filename

Die Request führe ich so aus:

PHP Code:
Dim proxy As String proxyServer

        
Try
            
request CType(HttpWebRequest.Create(url), HttpWebRequest)
            
request.Method "POST"
            
request.CookieContainer cookie
            request
.UserAgent "Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0"
            
request.Timeout NumericUpDown2.Value
            
If proxy <> "" Then
                request
.Proxy = New WebProxy(proxy)
            
End If

            If 
accept <> "" Then
                request
.Accept accept
            End 
If
            If 
content <> "" Then
                request
.ContentType content
            End 
If
            If 
referer <> "" Then
                request
.Referer referer
            End 
If

            
Dim byteArr() As Byte Encoding.UTF8.GetBytes(post)
            
request.ContentLength byteArr.Length

            Dim dataStream 
As Stream request.GetRequestStream()
            
dataStream.Write(byteArr0byteArr.Length)
            Try
                
response CType(request.GetResponse(), HttpWebResponse)
            Catch 
ex As Exception

            End 
Try

            Return New 
StreamReader(response.GetResponseStream()).ReadToEnd()

        Catch 
ex As Exception
            
Return "ERROR"
        
End Try 
Aber jetzt wird einfach nur das gesendet :O

[Only registered and activated users can see links. Click Here To Register...]
09/23/2013 22:59 BlackWu#4
Warum benutzt du nicht die API?
09/24/2013 20:21 allCoding#5
Quote:
Originally Posted by BlackWu View Post
Warum benutzt du nicht die API?
Was soll die unnötige post denn?

Er versucht doch eine Request zu basteln via API um damit den Decaptcher.org nutzen zu können.

Falls du ein konkretes Beispiel hast (Request), dann zeig sie doch.
09/24/2013 20:53 BlackWu#6
Quote:
Originally Posted by allCoding View Post
Was soll die unnötige post denn?

Er versucht doch eine Request zu basteln via API um damit den Decaptcher.org nutzen zu können.

Falls du ein konkretes Beispiel hast (Request), dann zeig sie doch.
Der ganze Thread ist unnötig.

Nach einer Sekunde auf der Seite gefunden.
Code:
using System;
using System.Text;
using System.IO;
using System.Net;

namespace CaptchaClient
{
	
	public static class SampleUse
	{
	
		public static void SampleSolve()
		{
			string ExampleFile="test.jpeg";
			CaptchaSolver solver=new CaptchaSolver("http://www.fasttypers.org/imagepost.ashx",
			                                     "KLJFSDFJLLG9KJT5IOEIWE839823K");
			
			if (solver.SolveCaptcha(ExampleFile))
			{
				string CaptchaText=solver.LastResponseText;
				//if you think that captchaText is not correct
				//Claim your refund
				//like solver.RefundLastTask(); or solver.refund(solver.LastTaskId);
			}else
			{
				//do actions based solver.LastPostState
				
			}
		
		}
	}
	
	public class CaptchaSolver
	{
		#region Attributes
		private string _PostUrl;
		private string _AccessKey;
		private string _VendorKey;
		private string _LastResponseText;
		private string _LastTaskId;
		private ResponseState _LastPostState;
		#endregion
		
		#region AttributeMehodes
		public string LastTaskId {
			get { return _LastTaskId; }
		}
		public ResponseState LastPostState {
			get { return _LastPostState; }
		}
		public string LastResponseText {
			get { return _LastResponseText; }
		}
		public string AccessKey {
			get { return _AccessKey; }
		}
		public string VendorKey {
			get { return _VendorKey; }
		}
		public string PostUrl {
			get { return _PostUrl; }
		}
		#endregion
		
		public CaptchaSolver(string ImagePostUrl,string Key, string PartnerVendorKey)
		{
			this._PostUrl=ImagePostUrl;
			this._AccessKey=Key;
			this._VendorKey=PartnerVendorKey;
		}
			public CaptchaSolver(string ImagePostUrl,string Key)
		{
			this._PostUrl=ImagePostUrl;
			this._AccessKey=Key;
			this._VendorKey="";
		}
		#region PrivateMethods
		private  string EncodeUrl(string str)
		{
			if (str == null) return "";

			Encoding enc = Encoding.ASCII;
			StringBuilder result = new StringBuilder();

			foreach (char symbol in str)
			{
				byte[] bs = enc.GetBytes(new char[] { symbol });
				for (int i = 0; i < bs.Length; i++)
				{
					byte b = bs[i];
					if (b >= 48 && b < 58 || b >= 65 && b < 65 + 26 || b >= 97 && b < 97 + 26) // decode non numalphabet
					{
						result.Append(Encoding.ASCII.GetString(bs, i, 1));
					}
					else
					{
						result.Append('%' + String.Format("{0:X2}", (int)b));
					}
				}
			}

			return result.ToString();
		}
		private  void Post( params string[] ps)
		{
			try
			{
				this._LastResponseText="";
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.PostUrl);
				request.Proxy = WebRequest.DefaultWebProxy;
				string str = "";
				
				for (int i = 0; i + 1 < ps.Length; i += 2)
				{
					str += EncodeUrl(ps[i]) + "=" + EncodeUrl(ps[i + 1]) + "&";
				}
				if (str.EndsWith("&"))
				{
					str = str.Substring(0, str.Length - 1);
				}

				request.Method = "POST";
				request.ContentType = "application/x-www-form-urlencoded";
				byte[] buffer = Encoding.ASCII.GetBytes(str);
				request.ContentLength = buffer.Length;
				Stream newStream = request.GetRequestStream();
				newStream.Write(buffer, 0, buffer.Length);

				WebResponse response = request.GetResponse();
				Stream sStream = response.GetResponseStream();
				StreamReader reader = new StreamReader(sStream);
				string ResponseSt = reader.ReadToEnd();
				this.DecodeResponse(ResponseSt);
				reader.Close();
				response.Close();
				newStream.Close();
				
			}
			catch
			{
				this._LastResponseText="";
			}
		}
		
		
		private void DecodeResponse(string ResponseSt)
		{
			this._LastResponseText="";
			char[] split=new char[]{' '};
			string[]splitMessage=ResponseSt.Split(split,StringSplitOptions.RemoveEmptyEntries);
			if (splitMessage.Length>1 && splitMessage[0]=="Error")
			{
				
				switch(splitMessage[1])
				{
					case "INCORRECT_ID":
						this._LastPostState= ResponseState.INCORRECT_ACCESS_KEY;
						break;
					case "NOT_ENOUGH_FUND":
						this._LastPostState = ResponseState.NOT_ENOUGH_FUND;
						break;
					case "TIMEOUT":
						this._LastPostState= ResponseState.TIMEOUT;
						break;
					case "INVALID_REQUEST":
						this._LastPostState=ResponseState.INVALID_REQUEST;
						break;
					case "UNKNOWN":
						this._LastPostState=ResponseState.UNKNOWN;
						break;
					default:
						this._LastPostState= ResponseState.OK;
						break;
				}
				
			}
			else 
			{
				this._LastPostState= ResponseState.OK;
				this._LastResponseText=ResponseSt;
			}
			
			
		}
		#endregion
		#region PublicMethods
		public  bool SolveCaptcha(string imageFileLocation)
		{
			this._LastTaskId=Guid.NewGuid().ToString();

			// read image data
			byte[] buffer = File.ReadAllBytes(imageFileLocation);

			// base64 encode it
			string img = Convert.ToBase64String(buffer);

			// submit captcha to server
			Post( new string[] {
			     	"action","upload",
			     	"vendorkey",this.VendorKey,
			     	"key", this.AccessKey,
			     	"file", img,
			     	"gen_task_id", this._LastTaskId});
			
			if (this.LastPostState== ResponseState.OK)
			{
				return true ;
			}
			else
			{
				return false;
			}
		}
		public bool RefundLastTask()
		{
			return Refund(this.LastTaskId);
		}
		public  bool Refund( string task_id)
		{
			
			Post( new string[] {
			     	"action","refund",
			     	"key", this.AccessKey,
			     	"gen_task_id", task_id});
			
			if (this.LastPostState== ResponseState.OK)
			{
				return true;
			}
			else
			{
				return false;
			}
			
		}
		public  int Balance()
		{
			try
			{
				
				Post( new string[] {
				     	"action","balance",
				     	"key", this.AccessKey
				     });
				if (this.LastPostState== ResponseState.OK)
				{
					return Convert.ToInt32(this.LastResponseText);
				}
				else
				{
					return 0;
				}
			}
			catch
			{
				throw;
			}
		}
		#endregion
	}
	public enum ResponseState
	{
		OK,
		TIMEOUT,
		INVALID_REQUEST,
		INCORRECT_ACCESS_KEY,
		NOT_ENOUGH_FUND,
		UNKNOWN,
	}
}
09/24/2013 21:15 maxasoft#7
Ok, ich schaue mal ob ich das in VB auch hinbekomme ._.
09/24/2013 21:19 tolio#8
[Only registered and activated users can see links. Click Here To Register...] lässt grüßen
Code:
Imports System.Text
Imports System.IO
Imports System.Net

Namespace CaptchaClient

	Public NotInheritable Class SampleUse
		Private Sub New()
		End Sub

		Public Shared Sub SampleSolve()
			Dim ExampleFile As String = "test.jpeg"
			Dim solver As New CaptchaSolver("http://www.fasttypers.org/imagepost.ashx", "KLJFSDFJLLG9KJT5IOEIWE839823K")

			If solver.SolveCaptcha(ExampleFile) Then
					'if you think that captchaText is not correct
					'Claim your refund
					'like solver.RefundLastTask(); or solver.refund(solver.LastTaskId);
				Dim CaptchaText As String = solver.LastResponseText
					'do actions based solver.LastPostState

			Else
			End If

		End Sub
	End Class

	Public Class CaptchaSolver
		#Region "Attributes"
		Private _PostUrl As String
		Private _AccessKey As String
		Private _VendorKey As String
		Private _LastResponseText As String
		Private _LastTaskId As String
		Private _LastPostState As ResponseState
		#End Region

		#Region "AttributeMehodes"
		Public ReadOnly Property LastTaskId() As String
			Get
				Return _LastTaskId
			End Get
		End Property
		Public ReadOnly Property LastPostState() As ResponseState
			Get
				Return _LastPostState
			End Get
		End Property
		Public ReadOnly Property LastResponseText() As String
			Get
				Return _LastResponseText
			End Get
		End Property
		Public ReadOnly Property AccessKey() As String
			Get
				Return _AccessKey
			End Get
		End Property
		Public ReadOnly Property VendorKey() As String
			Get
				Return _VendorKey
			End Get
		End Property
		Public ReadOnly Property PostUrl() As String
			Get
				Return _PostUrl
			End Get
		End Property
		#End Region

		Public Sub New(ImagePostUrl As String, Key As String, PartnerVendorKey As String)
			Me._PostUrl = ImagePostUrl
			Me._AccessKey = Key
			Me._VendorKey = PartnerVendorKey
		End Sub
		Public Sub New(ImagePostUrl As String, Key As String)
			Me._PostUrl = ImagePostUrl
			Me._AccessKey = Key
			Me._VendorKey = ""
		End Sub
		#Region "PrivateMethods"
		Private Function EncodeUrl(str As String) As String
			If str Is Nothing Then
				Return ""
			End If

			Dim enc As Encoding = Encoding.ASCII
			Dim result As New StringBuilder()

			For Each symbol As Char In str
				Dim bs As Byte() = enc.GetBytes(New Char() {symbol})
				For i As Integer = 0 To bs.Length - 1
					Dim b As Byte = bs(i)
					If b >= 48 AndAlso b < 58 OrElse b >= 65 AndAlso b < 65 + 26 OrElse b >= 97 AndAlso b < 97 + 26 Then
						' decode non numalphabet
						result.Append(Encoding.ASCII.GetString(bs, i, 1))
					Else
						result.Append("%"C & [String].Format("{0:X2}", CInt(b)))
					End If
				Next
			Next

			Return result.ToString()
		End Function
		Private Sub Post(ParamArray ps As String())
			Try
				Me._LastResponseText = ""
				Dim request As HttpWebRequest = DirectCast(WebRequest.Create(Me.PostUrl), HttpWebRequest)
				request.Proxy = WebRequest.DefaultWebProxy
				Dim str As String = ""

				Dim i As Integer = 0
				While i + 1 < ps.Length
					str += EncodeUrl(ps(i)) & "=" & EncodeUrl(ps(i + 1)) & "&"
					i += 2
				End While
				If str.EndsWith("&") Then
					str = str.Substring(0, str.Length - 1)
				End If

				request.Method = "POST"
				request.ContentType = "application/x-www-form-urlencoded"
				Dim buffer As Byte() = Encoding.ASCII.GetBytes(str)
				request.ContentLength = buffer.Length
				Dim newStream As Stream = request.GetRequestStream()
				newStream.Write(buffer, 0, buffer.Length)

				Dim response As WebResponse = request.GetResponse()
				Dim sStream As Stream = response.GetResponseStream()
				Dim reader As New StreamReader(sStream)
				Dim ResponseSt As String = reader.ReadToEnd()
				Me.DecodeResponse(ResponseSt)
				reader.Close()
				response.Close()

				newStream.Close()
			Catch
				Me._LastResponseText = ""
			End Try
		End Sub


		Private Sub DecodeResponse(ResponseSt As String)
			Me._LastResponseText = ""
			Dim split As Char() = New Char() {" "C}
			Dim splitMessage As String() = ResponseSt.Split(split, StringSplitOptions.RemoveEmptyEntries)
			If splitMessage.Length > 1 AndAlso splitMessage(0) = "Error" Then

				Select Case splitMessage(1)
					Case "INCORRECT_ID"
						Me._LastPostState = ResponseState.INCORRECT_ACCESS_KEY
						Exit Select
					Case "NOT_ENOUGH_FUND"
						Me._LastPostState = ResponseState.NOT_ENOUGH_FUND
						Exit Select
					Case "TIMEOUT"
						Me._LastPostState = ResponseState.TIMEOUT
						Exit Select
					Case "INVALID_REQUEST"
						Me._LastPostState = ResponseState.INVALID_REQUEST
						Exit Select
					Case "UNKNOWN"
						Me._LastPostState = ResponseState.UNKNOWN
						Exit Select
					Case Else
						Me._LastPostState = ResponseState.OK
						Exit Select

				End Select
			Else
				Me._LastPostState = ResponseState.OK
				Me._LastResponseText = ResponseSt
			End If


		End Sub
		#End Region
		#Region "PublicMethods"
		Public Function SolveCaptcha(imageFileLocation As String) As Boolean
			Me._LastTaskId = Guid.NewGuid().ToString()

			' read image data
			Dim buffer As Byte() = File.ReadAllBytes(imageFileLocation)

			' base64 encode it
			Dim img As String = Convert.ToBase64String(buffer)

			' submit captcha to server
			Post(New String() {"action", "upload", "vendorkey", Me.VendorKey, "key", Me.AccessKey, _
				"file", img, "gen_task_id", Me._LastTaskId})

			If Me.LastPostState = ResponseState.OK Then
				Return True
			Else
				Return False
			End If
		End Function
		Public Function RefundLastTask() As Boolean
			Return Refund(Me.LastTaskId)
		End Function
		Public Function Refund(task_id As String) As Boolean

			Post(New String() {"action", "refund", "key", Me.AccessKey, "gen_task_id", task_id})

			If Me.LastPostState = ResponseState.OK Then
				Return True
			Else
				Return False
			End If

		End Function
		Public Function Balance() As Integer
			Try

				Post(New String() {"action", "balance", "key", Me.AccessKey})
				If Me.LastPostState = ResponseState.OK Then
					Return Convert.ToInt32(Me.LastResponseText)
				Else
					Return 0
				End If
			Catch
				Throw
			End Try
		End Function
		#End Region
	End Class
	Public Enum ResponseState
		OK
		TIMEOUT
		INVALID_REQUEST
		INCORRECT_ACCESS_KEY
		NOT_ENOUGH_FUND
		UNKNOWN
	End Enum
End Namespace
10/25/2013 01:07 li0nsar3c00l#9
das problem liegt vor allem darin, dass sobald du das bild hochgeladen hast auf die response warten musst. die steht nicht gleich in quellcode