Open Feign Client Use JSON String (with curly braces) as Header - openfeign

I tried to set this JSON string to a header for open feign client
**apiheader**={"digitalSignature": "digitalSignature", "timeoutTime": "0", "headerVersion": "1.0", "correlation": { "requestId": "0e34c7cf-1fc5-457d-9593-646edba4d3d8", "myId": "T0TPart042715545524b4-fef5-4b97-86e0-f738bddec8c2", "myTimeStamp": "2017-03-30T15:41:04.575-04:00", "callPath": "GetData", "keyValues": " " }, "who": { "employeeUserId": "TEST12", "partyMultiFactorAuthenticationIndicator": "WERTY" } }
But feign client cut it off to soemthing like this in log, this will cause invalid header. Can anyone help on this case? Looks like feign client treat the JSON string as an expression rather than a normal header.
---> POST https://sit1.hostname.net:6007/GetData HTTP/1.1
**apiheader: {"digitalSignature": "digitalSignature", "timeoutTime"}**
Content-Length: 283
Content-Type: application/json
**Below is the Feign client interface:**
#FeignClient(name = "postFeignClient", url = "https://sit1.hostname.net:6007/", configuration = {FeignClientsConfiguration.class, SSLFeignClientConfig.class})
public interface GetDataApi {
#PostMapping(value="/GetData")
#Headers({
"Content-type: application/json; charset=utf-8",
"Accepts: application/json",
"apiheader: {apiheader}"
})
GetDataResponse getData(
#RequestHeader(value="apiheader") String apiheader,
GetDataRequest body);
}
FeignClient Configuration
#Configuration
public class SSLFeignClientConfig {
#Bean
#Scope("prototype")
#ConditionalOnMissingBean
public Feign.Builder feignBuilder() {
Client client;
Optional<SSLSocketFactoryConfig> socketFactory = SSLContextSocketFactory.loadSocketFactoryConfig();
try {
SSLContext context = SSLContextSocketFactory.loadSSLContext();
client = new Client.Default(context.getSocketFactory(), new NoopHostnameVerifier());
} catch (Exception e) {
logger.error("Create feign client with SSL config failed", e);
client = new Client.Default(null, null);
}
return Feign.builder().client(client);
}
}
Controller:
#Autowired
GetDataApi getDataApi;
#GetMapping(value="/test")
public GetDataResponse getData() throws IOException {
GetDataResponse response;
GetDataRequest request=new GetDataRequest();
String apiheader="{\"digitalSignature\": \"digitalSignature\", \"timeoutTime\": \"0\", \"headerVersion\": \"1.0\", \"correlation\": { \"requestId\": \"0e34c7cf-1fc5-457d-9593-646edba4d3d8\", \"myId\": \"T0TPart042715545524b4-fef5-4b97-86e0-f738bddec8c2\", \"myTimeStamp\": \"2017-03-30T15:41:04.575-04:00\", \"callPath\": \"GetData\", \"keyValues\": \" \" }, \"who\": { \"employeeUserId\": \"TEST12\", \"partyMultiFactorAuthenticationIndicator\": \"WERTY\" }, \"what\": { \"API\": \"GetData\", \"APIFunction\": \"Submit\", \"keyValues\": \" \" }, \"where\": { \"originatorLocationId\": \"111\", \"originatorLocationType\": \"OnLine\", \"originatorApplicationCatalogueId\": \"111\", \"originatorChannel\": \"CC\", \"originatorSessionId\": \"632587415\", \"keyValues\": \" \" }}";
response=getDataApi.getData(apiheader, request);
return response;
}
POM dependency:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
<version>11.8</version>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
I tried to set this JSON string to a header for open feign client
apiheader={"digitalSignature": "digitalSignature", "timeoutTime": "0", "headerVersion": "1.0", "correlation": { "requestId": "0e34c7cf-1fc5-457d-9593-646edba4d3d8", "myId": "T0TPart042715545524b4-fef5-4b97-86e0-f738bddec8c2", "myTimeStamp": "2017-03-30T15:41:04.575-04:00", "callPath": "GetData", "keyValues": " " }, "who": { "employeeUserId": "TEST12", "partyMultiFactorAuthenticationIndicator": "WERTY" } }
But feign client cut it off to soemthing like this in log, this will cause invalid header. Can anyone help on this case? Looks like feign client treat the JSON string as an expression rather than a normal header.
---> POST https://sit1.hostname.net:6007/GetData HTTP/1.1
apiheader: {"digitalSignature": "digitalSignature", "timeoutTime"}
Content-Length: 283
Content-Type: application/json
Can anyone help on this case?
Looks like feign client treat the JSON string as an expression rather than a normal header.

Related

AWS ALB of a Go Lambda always returns "502 Bad Gateway"

I have an AWS Lambda implemented with Go lang. The Lambda is triggered by an ALB. When I invoke the ALB from outside it always returns this:
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
</body>
</html>
In CloudWatch I can see that the Lambda was invoked. In this article I have read that the ALB expects a very specific response object from the Lambda. I have implemented that as a struct. Here is the Go Lambda code:
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"log"
)
type Request struct {
HttpMethod string `json:"httpMethod"`
Path string `json:"path"`
QueryStringParameters map[string]string `json:"queryStringParameters"`
IsBase64Encoded bool `json:"isBase64Encoded"`
Body string `json:"body"`
Headers RequestHeaders `json:"headers"`
}
type RequestHeaders struct {
Accept string `json:"accept"`
AcceptLanguage string `json:"accept-language"`
ContentType string `json:"Content-Type"`
Cookie string `json:"cookie"`
Host string `json:"host"`
UserAgent string `json:"user-agent"`
XAmznTraceId string `json:"x-amzn-trace-id"`
XForwardedFor string `json:"x-forwarded-for"`
XForwardedPort string `json:"x-forwarded-port"`
XForwardedProto string `json:"x-forwarded-proto"`
}
type Response struct {
IsBase64Encoded bool `json:"isBase64Encoded"`
StatusCode int `json:"statusCode"`
StatusDescription string `json:"statusDescription"`
Headers *ResponseHeaders `json:"headers"`
Body string `json:"body"`
}
type ResponseHeaders struct {
ContentType string `json:"Content-Type"`
}
func HandleRequest(ctx context.Context, request Request) (string, error) {
fmt.Println("Hello " + request.Body)
responseHeaders := new(ResponseHeaders)
responseHeaders.ContentType = "application/json"
response := new(Response)
response.IsBase64Encoded = false
response.StatusCode = 200
response.StatusDescription = "200 OK"
response.Headers = responseHeaders
response.Body = "{\"hello\":\"world\"}"
json, err := json.Marshal(response)
if err != nil {
log.Fatal(err)
}
responseString := string(json)
log.Println(responseString)
return responseString, nil
}
func main() {
lambda.Start( HandleRequest )
}
In Cloudwatch I can see that the Lambda is invoked and this the string it returns:
{
"isBase64Encoded": false,
"statusCode": 200,
"statusDescription": "200 OK",
"headers": {
"Content-Type": "application/json"
},
"body": "{\"hello\":\"world\"}"
}
As far as I can tell it looks like the described response specification in this article.
The logs from the ALB itself look like this:
http 2020-07-13T11:49:51.014327Z app/test-Lambda/3e92b31e6a921454 176.199.208.26:54486 - 0.006 0.021 -1 502 - 736 293 "POST http://test-lambda-999999999.eu-central-1.elb.amazonaws.com:80/ HTTP/1.1" "insomnia/7.1.1" - - arn:aws:elasticloadbalancing:eu-central-1:999999999:targetgroup/test-lambda-target/540454d9390da765 "Root=1-5f0c4a5e-ca4e4a43b6c48633dc4c5b3e" "-" "-" 0 2020-07-13T11:49:50.986000Z "forward" "-" "LambdaInvalidResponse" "-" "-"
I invested already a couple of hours in debugging but I really don't know why the ALB always returns a 502 error. Can you see the error? What I'm doing wrong?
Solved via debugging in comments: you need to return your actual Response structure from the handler, not a string containing JSON. The lambda library handles serializing the return value to JSON on its own.

Java RESTEasy WebService - Download the image file from HTTPResponse object.

I need to download a image files from the file system using RESTEasy web service and the input httpclient is JSON and the output response is
#Produces({"image/jpeg,image/png"})
Here is my client code:
public void getFileDownload(){
log("inside getServerPath....");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(downloadWebService_URL);
JSONObject json = new JSONObject();
json.put("filePath", "/ngs/app/sample.png");
json.put("fileName", "sample.png");
log("json-->"+json.toString());
StringEntity inputJson = null;
try {
inputJson = new StringEntity(json.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
log("inputJson = " + inputJson.toString());
inputJson.setContentType("application/json");
httpPost.setEntity(inputJson);
httpPost.addHeader("AppType", "TC");
log("httpPost... httpPost");
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
log("response:-->"+response);
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
log("E:: " + ExceptionUtils.getStackTrace(e));
}
}
Here is my Webservice code:
#Path("/downloadservice")
public class DownloadFileWS {
private static final String FILE_PATH = "/ngs/app/sample.png";
#POST
// #Path("/images")
#Path("/{fileName}/images")
#Consumes({"application/json"})
#Produces({"image/jpeg,image/png"})
public Response getImageFile(#PathParam("fileName") String fileName) {
File file = new File(FILE_PATH);
System.out.println("File requested is : " + fileName);
Logger.getLogger("!!!!!!!!!!!"+FILE_PATH);
System.out.println("########"+FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"sample.png\"");
return response.build();
}
The HTTP Response is:
response:-->HTTP/1.1 200 OK [Date: Tue, 19 Jul 2016 00:36:22 GMT,
Content-Length: 6192, Content-Type: image/png, Content-Disposition:
attachment; filename="sample.png", X-Powered-By: Servlet/2.5 JSP/2.1]
org.apache.http.conn.BasicManagedEntity#2ace1307
Question:
1. Based on the response, it looks like the service is sending the image in HTTPResponse object. May i know how to download the image received from HTTP Response?
2. The requirement is to click a link which calls the webservice by passing JSON as input request and the image should automatically download to the user's local machine browser.

RESTful webservice using Spring mvc respond back with data file as response

How can i respond back with a text file containing json data upon request from client .
The request url is:
http://localhost:8082/web/ws/datafileid/json/Sat May 16 12:05:07 IST 2015.txt/
Controller code that handles the request is:
#RequestMapping(value=EmpRestURIConstants.DATAFILE_REQUEST,method=RequestMethod.GET)
#ResponseBody
public String datafileresponse(#PathVariable("filename") String filename, HttpServletResponse response) {
return cinehomeRestService.checkfilevalid(filename);
}
Service class that handles the request to check the file exists is:
#Override
public String checkfilevalid(String filename) {
String datafilename=webServiceDao.getdatafilename();
JSONObject obj = new JSONObject();
if(datafilename.equals(filename)) {
return "file";
}
else {
try {
obj.put("status", "022");
} catch (JSONException e) {
e.printStackTrace();
}
return obj.toString();
}
}
Here I need to respond back with the datafile.txt that exists at location resources. How can I perform the task. Can anyone help?
i have tried a method
#RequestMapping(value=EmpRestURIConstants.DATAFILE_REQUEST,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Response datafileresponse(#PathVariable("filename")String filename) throws IOException{
JSONObject readdata = new JSONObject();
String uploadPath = servletContext.getRealPath("");
String fullyqualifiedfilename=uploadPath+filename;
System.out.println("+++++++++"+fullyqualifiedfilename);
return Response.ok(uploadPath)
.header("Content-Disposition", "attachment; filename=\"" + fullyqualifiedfilename + "\"" ) //optional
.build();
}
i GOT THE REPLY AS...
{ "statusType": "OK", "entity": /home/cine/WORKSPACES/study/.metadata/.plugins/org.eclipse.wst.server.‌​core/tmp0/wtpwebapps/
"entityType": "java.lang.String", "metadata": { "Content-Disposition": [ "attachment;
filename="/home/cine/WORKSPACES/study/.metadata/.plugins/org.eclipse.wst.server.‌​core/tmp0/wtpwebapps/Cine Sat May 16 12:05:07 IST 2015.txt"" ] }, "status": 200 }
What this status means. Does the client can fetch teh file using this response.??

Testing ASP.NET Web API Multipart Form Data File upload

I am trying to use N-UNIT to test my web API application but I am unable to find a proper way to test my file upload method. Which would be the best approach to test the method?
Web API Controller:
[AcceptVerbs("post")]
public async Task<HttpResponseMessage> Validate()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"please submit a valid request");
}
var provider = new MultipartMemoryStreamProvider(); // this loads the file into memory for later on processing
try
{
await Request.Content.ReadAsMultipartAsync(provider);
var resp = new HttpResponseMessage(HttpStatusCode.OK);
foreach (var item in provider.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
Stream stream = item.ReadAsStreamAsync().Result;
// do some stuff and return response
resp.Content = new StringContent(result, Encoding.UTF8, "application/xml"); //text/plain "application/xml"
return resp;
}
}
return resp;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
Based on your above comment, following is an example:
HttpClient client = new HttpClient();
MultipartFormDataContent formDataContent = new MultipartFormDataContent();
formDataContent.Add(new StringContent("Hello World!"),name: "greeting");
StreamContent file1 = new StreamContent(File.OpenRead(#"C:\Images\Image1.jpeg"));
file1.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file1.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file1);
StreamContent file2 = new StreamContent(File.OpenRead(#"C:\Images\Image2.jpeg"));
file2.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file2.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file2);
HttpResponseMessage response = client.PostAsync("http://loclhost:9095/api/fileuploads", formDataContent).Result;
The request over the wire would like:
POST http://localhost:9095/api/fileuploads HTTP/1.1
Content-Type: multipart/form-data; boundary="34d56c28-919b-42ab-8462-076b400bd03f"
Host: localhost:9095
Content-Length: 486
Expect: 100-continue
Connection: Keep-Alive
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=greeting
Hello World!
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image1.jpeg
----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image2.jpeg
----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f--
After spending a bit of time looking into WebClient I was able to come up with this:
try
{
var imageFile = Path.Combine("dir", "fileName");
WebClient webClient = new WebClient();
byte[] rawResponse = webClient.UploadFile(string.Format("{0}/api/values/", "http://localhost:12345/"), imageFile);
Console.WriteLine("Sever Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse)); // for debugging purposes
Console.WriteLine("File Upload was successful");
}
catch (WebException wexc)
{
Console.WriteLine("Failed with an exception of " + wexc.Message);
// anything other than 200 will trigger the WebException
}

Asmx web service basic authentication

I want to implement basic authentication using username and password validation in my asmx web service.
I don't want to use WCF and I know this is not secure way, but I need to use basic authentication without using https.
My web service is like this:
[WebService(Namespace = "http://www.mywebsite.com/")]
public class Service1
{
[WebMethod]
public string HelloWorld()
{
return "Hello world";
}
}
And I use this custom HttpModule:
public class BasicAuthHttpModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(OnAuthenticateRequest);
}
void OnAuthenticateRequest(object sender, EventArgs e)
{
string header = HttpContext.Current.Request.Headers["Authorization"];
if (header != null && header.StartsWith("Basic")) //if has header
{
string encodedUserPass = header.Substring(6).Trim(); //remove the "Basic"
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass));
string[] credentials = userPass.Split(':');
string username = credentials[0];
string password = credentials[1];
if(!MyUserValidator.Validate(username, password))
{
HttpContext.Current.Response.StatusCode = 401;
HttpContext.Current.Response.End();
}
}
else
{
//send request header for the 1st round
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", string.Empty));
}
}
void IHttpModule.Dispose()
{
}
}
And in the web.config I use this:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="None"/>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="BasicAuthHttpModule"
type="AuthService.BasicAuthHttpModule, AuthService" />
</modules>
</system.webServer>
</configuration>
The calling code is:
static void Main(string[] args)
{
var proxy = new Service1.Service1()
{
Credentials = new NetworkCredential("user1", "p#ssw0rd"),
PreAuthenticate = true
};
try
{
var result = proxy.HelloWorld();
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
when I use this web service, the service asks for basic authentication but header variable in the OnAuthenticateRequest method always is null and MyUserValidator.Validate() never run.
EDIT
The fiddler results:
POST http://www.mywebsite.com/Service1.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)
VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.mywebsite.com/HelloWorld"
Host: www.mywebsite.com
Content-Length: 291
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld xmlns="http://www.mywebsite.com/" /></soap:Body></soap:Envelope>
HTTP/1.1 401 Unauthorized
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Basic realm=""
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Basic realm="www.mywebsite.com"
X-Powered-By: ASP.NET
Date: Sun, 03 Jun 2012 07:14:40 GMT
Content-Length: 1293
------------------------------------------------------------------
POST http://www.mywebsite.com/Service1.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)
VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.mywebsite.com/HelloWorld"
Authorization: Basic dXNlcjE6cEBzc3cwcmQ=
Host: www.mywebsite.com
Content-Length: 291
Expect: 100-continue
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld xmlns="http://www.mywebsite.com/" /></soap:Body></soap:Envelope>
HTTP/1.1 401 Unauthorized
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Basic realm="www.mywebsite.com"
X-Powered-By: ASP.NET
Date: Sun, 03 Jun 2012 07:14:41 GMT
Content-Length: 1293
------------------------------------------------------------------
Change your custom HttpModule code to this:
public class BasicAuthHttpModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.AuthenticateRequest += new
EventHandler(this.OnAuthenticateRequest);
application.EndRequest += new
EventHandler(this.OnEndRequest);
}
public void OnAuthenticateRequest(object source, EventArgs
eventArgs)
{
HttpApplication app = (HttpApplication)source;
string authHeader = app.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
string authStr = app.Request.Headers["Authorization"];
if (authStr == null || authStr.Length == 0)
{
return;
}
authStr = authStr.Trim();
if (authStr.IndexOf("Basic", 0) != 0)
{
return;
}
authStr = authStr.Trim();
string encodedCredentials = authStr.Substring(6);
byte[] decodedBytes =
Convert.FromBase64String(encodedCredentials);
string s = new ASCIIEncoding().GetString(decodedBytes);
string[] userPass = s.Split(new char[] { ':' });
string username = userPass[0];
string password = userPass[1];
if (!MyUserValidator.Validate(username, password))
{
DenyAccess(app);
return;
}
}
else
{
app.Response.StatusCode = 401;
app.Response.End();
}
}
public void OnEndRequest(object source, EventArgs eventArgs)
{
if (HttpContext.Current.Response.StatusCode == 401)
{
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", "Basic Realm");
}
}
private void DenyAccess(HttpApplication app)
{
app.Response.StatusCode = 401;
app.Response.StatusDescription = "Access Denied";
app.Response.Write("401 Access Denied");
app.CompleteRequest();
}
}
Then enable Anonymous authentication and disable Basic, Digest and Windows authentication for your website in IIS.
Note: This implementation will work with WCF too.
It seems that you need send the headers manually the first time:
from Rick Strahl's Blog
string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
string user = "ricks";
string pwd = "secret";
string domain = "www.west-wind.com";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
req.PreAuthenticate = true;
req.Headers.Add("Authorization", auth);
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
WebResponse resp = req.GetResponse();
resp.Close();