cannot instantiate the type httpclient in android - httpclient

Am getting an error with the following line of code
HttpClient Client= new HttpClient.
I have tried rewriting it as HttpClient Client= new DefaultHttpClient. but it solves the problem and creates a new error with other methods
.
Here is a glimpse of my code
protected static MDSResult doExecute(Context ctx, HttpMethod method){
HttpClient client = new HttpClient();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(ctx);
MDSResult response = null;
// If there's a proxy enabled, use it.
String proxyHost = preferences.getString(
Constants.PREFERENCE_PROXY_HOST, "");
String sProxyPort = preferences.getString(
Constants.PREFERENCE_PROXY_PORT, "0");
boolean useSecure = preferences.getBoolean(
Constants.PREFERENCE_SECURE_TRANSMISSION, false);
int proxyPort = 0;
try {
if (!"".equals(sProxyPort))
proxyPort = Integer.parseInt(sProxyPort);
} catch(NumberFormatException e) {
Log.w(TAG, "Invalid proxy port: " + sProxyPort);
}
if (!"".equals(proxyHost) && proxyPort != 0) {
Log.i(TAG, "Setting proxy to " + proxyHost + ":" + proxyPort);
HostConfiguration hc = new HostConfiguration();
hc.setProxy(proxyHost, (int)proxyPort);
client.setHostConfiguration(hc);
}
// execute the Http/https method
try {
if(useSecure){
ProtocolSocketFactory ssl = new SimpleSSLProtocolSocketFactory();
Protocol https = new Protocol("https", ssl, 443);
Protocol.registerProtocol("https", https);
}
int status = client.executeMethod(method);
Log.d(TAG, "postResponses got response code " + status);
char buf[] = new char[20560];
Reader reader = new InputStreamReader(
method.getResponseBodyAsStream());
int total = reader.read(buf, 0, 20560);
String responseString = new String(buf);
Log.d(TAG, "Received from MDS:" + responseString.length()+" chars");
Gson gson = new Gson();
response = gson.fromJson(responseString, MDSResult.class);
}

You want DefaultHttpClient, not HttpClient like you mentioned. HttpClient is abstract so cannot be instantiated.
HttpClient client = new DefaultHttpClient();
What is the error with the other methods when you use that ?
Also why not use HttpURLConnection ? I find it much more reliable.

Related

VSTS Web Api gives 403 unauthoratative response

I have created a native app in Azure using App Registration and added required permissions for VSTS Agent
Now, I am able to login using oauth authentication with "ADAL" and able to get the token but when trying to access the web api request it gives Http 403 Response
Here is the code example below
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
HttpResponseMessage res = client.GetAsync(webapiURL).Result;
}
Please let me know what i am missing
thanks in advance
Seems it's an authentication issue, Just check the value of authHeader.
You can reference below samples for the authentication with header:
Sample 1- auth-samples here ;
Sample 2 - REST API
Post the auth sample as reference here:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
namespace DeviceProfileSample
{
public class Program
{
//============= Config [Edit these with your settings] =====================
internal const string vstsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS account; NOTE: This must use HTTPS
internal const string clientId = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1"; //update this with your Application ID from step 2.6 (do not change this if you have an MSA backed account)
//==========================================================================
internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Static value to target VSTS. Do not change
public static void Main(string[] args)
{
AuthenticationContext ctx = GetAuthenticationContext(null);
AuthenticationResult result = null;
try
{
DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync(VSTSResourceId, clientId).Result;
Console.WriteLine("You need to sign in.");
Console.WriteLine("Message: " + codeResult.Message + "\n");
result = ctx.AcquireTokenByDeviceCodeAsync(codeResult).Result;
var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
ListProjects(bearerAuthHeader);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Something went wrong.");
Console.WriteLine("Message: " + ex.Message + "\n");
}
}
private static AuthenticationContext GetAuthenticationContext(string tenant)
{
AuthenticationContext ctx = null;
if (tenant != null)
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
else
{
ctx = new AuthenticationContext("https://login.windows.net/common");
if (ctx.TokenCache.Count > 0)
{
string homeTenant = ctx.TokenCache.ReadItems().First().TenantId;
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant);
}
}
return ctx;
}
private static void ListProjects(AuthenticationHeaderValue authHeader)
{
// use the httpclient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "VstsRestApiSamples");
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
// connect to the REST endpoint
HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=2.2").Result;
// check to see if we have a succesfull respond
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\tSuccesful REST call");
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
}
}
}
}
}
Aren't you missing what authentication,
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token)));
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials)
HttpResponseMessage response = client.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync();
}
I hope this helps.

Websphere App Server 7.0.0.43 - IBM Java 1.6, Apache Wink, Rest Client TLSv1.2

Recently upgraded websphere app server to TLSv1.2. Prior, with TLSv1, was able to interface with REST client using combination of javax.ws.rs, org.glassfish.jersey and javax.net.ssl. Wasn't able to get working once app server upgraded TLS. IBM instructed to apply Feature Pack Web 2.0 and interface with REST client using Apache Wink. Haven't been able to get this solution to work. Previously, Keystore and Truststore were set on SSLContext.
private static String getClient(String servicePath){
try {
javax.ws.rs.client.Client client = null;
org.glassfish.jersey.client.ClientConfig clientConfig = new org.glassfish.jersey.client.ClientConfig();
int readTimeOut = Integer.parseInt(commonProp.getProperty(READ_TIMEOUT));
int connTimeout = Integer.parseInt(commonProp.getProperty(CONNECTION_TIMEOUT));
clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connTimeout);
clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeOut);
org.glassfish.jersey.SslConfigurator sslConfig;
String trustStoreName = commonProp.getProperty(TRUSTSTORE_NAME);
File file1 = new File("\\"+PROJECT_FILE_DIR+ "/ISB"+trustStoreName.trim());
String keyStoreName = commonProp.getProperty(KEYSTORE_NAME);
File file2 = new File("\\"+PROJECT_FILE_DIR+ "/ISB"+keyStoreName.trim());
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
String trustStorePassword = commonProp.getProperty(TRUSTSTORE_PASSWORD);
String keyStorePassword = commonProp.getProperty(KETSTORE_PASSWORD);
sslConfig = org.glassfish.jersey.SslConfigurator.newInstance().trustStoreBytes(ByteStreams.toByteArray(fis1))
.trustStorePassword(trustStorePassword).keyStoreBytes(ByteStreams.toByteArray(fis2))
.keyPassword(keyStorePassword);
javax.net.ssl.SSLContext sslContext = sslConfig.createSSLContext();
client = javax.ws.rs.client.ClientBuilder.newBuilder().sslContext(sslContext).withConfig(clientConfig).build();
String url = commonProp.getProperty(ENDPOINT_URL)+servicePath;
Response response =
client.target(url)
.request(MediaType.APPLICATION_JSON)
.get();
String responseAsString = "";
if(response != null){
responseAsString = response.readEntity(String.class);
}
return responseAsString;
} catch (Throwable e) {
logger.severe(e.getMessage() + e.getLocalizedMessage());
e.printStackTrace();
throw new RuntimeException(e);
}
}
With Installed Feature Pack and use of JSSEHELPER, retrieved SSL alias
information from WAS. Seem to make client connection now, but still have
authentication issue
Blockquote
response statusCode: 200
called close()
called closeInternal(true)
WebContainer : 0, SEND TLSv1.2 ALERT: warning, description = close_notify
An attempt to authenticate with a client certificate failed. A valid client
certificate is required to make this connection.
Blockquote
Believe issue may be that previously the KEYSTORE and TRUSTSTORE information
was read from file. Whereas the JSSEHELPER is simply putting file name.
com.ibm.ssl.clientAuthenticationSupported = false
com.ibm.ssl.keyStoreClientAlias = isbgatewaytst
com.ibm.ssl.contextProvider = IBMJSSE2
com.ibm.ssl.trustStoreProvider = IBMJCE
com.ibm.ssl.protocol = TLSv1.2
com.ibm.ssl.keyStoreReadOnly = false
com.ibm.ssl.alias = ISBGatewaySSL
com.ibm.ssl.keyStoreCreateCMSStash = false
com.ibm.ssl.securityLevel = CUSTOM
com.ibm.ssl.trustStoreName = ISBGatewayTrust
com.ibm.ssl.configURLLoadedFrom = security.xml
com.ibm.ssl.trustStorePassword = ********
com.ibm.ssl.keyStoreUseForAcceleration = false
com.ibm.ssl.trustManager = PKIX
com.ibm.ssl.validationEnabled = false
com.ibm.ssl.trustStoreInitializeAtStartup = false
com.ibm.ssl.keyManager = IbmX509
com.ibm.ssl.keyStoreFileBased = true
com.ibm.ssl.keyStoreType = JKS
com.ibm.ssl.trustStoreFileBased = true
com.ibm.ssl.trustStoreCreateCMSStash = false
com.ibm.ssl.trustStoreScope = (cell):ESB_DEV
com.ibm.ssl.trustStore = E:/IBM/content/resources/dev_projectfiles_dir/ISB/isb-truststore.jks
com.ibm.ssl.keyStoreProvider = IBMJCE
com.ibm.ssl.enabledCipherSuites = SSL_ECDHE_RSA_WITH_AES_128_GCM_SHA256 SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256 SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA
com.ibm.ssl.daysBeforeExpireWarning = 60
com.ibm.ssl.keyStoreServerAlias = isbgatewaytst
com.ibm.ssl.clientAuthentication = false
com.ibm.ssl.keyStore = E:/IBM/content/resources/dev_projectfiles_dir/ISB/isb-keystore-tst.jks
com.ibm.ssl.trustStoreUseForAcceleration = false
com.ibm.ssl.trustStoreReadOnly = false
com.ibm.ssl.keyStoreScope = (cell):ESB_DEV
com.ibm.ssl.tokenEnabled = false
com.ibm.ssl.keyStoreName = ISBGatewayPrivatekey
com.ibm.ssl.keyStorePassword = ********
com.ibm.ssl.keyStoreInitializeAtStartup = false
com.ibm.ssl.trustStoreType = JKS
My issue is how to put the KEYSTORE and TRUSTSTORE information on the org.apache.wink.client.ClientConfig or else where, similar to previously setting the javax.net.ssl.SSLContext? Did set the WAS SSL alias information on the ClientConfig properties, but believe that is just adding the Store's file location which isn't of use for the REST Client.
public static String getPPLUResponseString(String servicePath) {
String responseAsString = "";
com.ibm.websphere.ssl.JSSEHelper jsseHelper = com.ibm.websphere.ssl.JSSEHelper.getInstance();
try {
Properties sslProps = null;
String alias = "ISBGatewaySSL";
sslProps = jsseHelper.getProperties(alias, getConnectionInfo(), null);
org.apache.wink.client.ClientConfig clientConfig = new org.apache.wink.client.ClientConfig();
clientConfig.readTimeout(Integer.parseInt(commonProp.getProperty(READ_TIMEOUT)));
clientConfig.connectTimeout(Integer.parseInt(commonProp.getProperty(CONNECTION_TIMEOUT)));
clientConfig.setProperties(sslProps);
Enumeration keys = clientConfig.getProperties().keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = (String) clientConfig.getProperties().get(key);
System.out.println(" clientConfig.getProperties(): " + key + ": " + value);
}
org.apache.wink.client.RestClient restClient = new org.apache.wink.client.RestClient(clientConfig);
String url = commonProp.getProperty(ENDPOINT_URL) + servicePath;
System.out.println(" url: " + url);
org.apache.wink.client.Resource restResource = restClient.resource(url);
System.out.println(" before client response");
org.apache.wink.client.ClientResponse clientResponse = restResource.accept(MediaType.APPLICATION_JSON_TYPE).get();
int statusCode = clientResponse.getStatusCode();
System.out.println(" response statusCode: " + statusCode);
String responseEntity = clientResponse.getEntity(String.class);
System.out.println(" responseEntity start: " + responseEntity);
System.out.println(" responseEntity end: ");
if (responseEntity != null) {
responseAsString = responseEntity;
}
} catch (com.ibm.websphere.ssl.SSLException e) {
System.out.println(" com.ibm.websphere.ssl.SSLException");
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseAsString;
}

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

Jetty Java websocket client doesn't connect to server

I am using Java Jetty client written [websocket-client 9.3.8.RC0]. Websocket server is little wierd in our case.
It accepting request in format.
wss://192.168.122.1:8443/status?-xsrf-=tokenValue
Token Value is received in first Login POST request in which i get Token Value & Cookie header. Cookie is added as a header whereas token is given as a param.
Now question is : -
When i run below code it just call awaitclose() function in starting. But there is not other function called i.e. Onconnected or even Onclose.
Any help would be appreciated to debug it further, to see any logs or environment issue to see why Socket is not connected.
Trying to figure out following points to debug.
1. To check if client certificates are causing issue.
Tried with my python code wspy.py it work seemlessly fine.
Code is
public final class websocketxxx {
WebSocketClient client=null;
public websocketxxx (){
}
public void run(String host,String cookieVal, String xsrfVal, String resource) throws IOException {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient client = new WebSocketClient(sslContextFactory);
MyWebSocket socket = new MyWebSocket();
try {
client.start();
ClientUpgradeRequest request = new ClientUpgradeRequest();
// Add the authentication and protocol to the request header
// Crate wss URI from host and resource
resource = resource + xsrfVal;
URI destinationUri = new URI("wss://" + host + resource); // set URI
request.setHeader("cookie",cookieVal);
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
//System.out.println("Request Headers print : " request.getHeaders())
System.out.println("Connecting to : " + destinationUri);
client.connect(socket, destinationUri, request);
socket.awaitClose(5000, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#WebSocket
public class MyWebSocket {
private final CountDownLatch closeLatch = new CountDownLatch(1);
#OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("WebSocket Opened in client side");
try {
System.out.println("Sending message: Hi server");
session.getRemote().sendString("Hi Server");
} catch (IOException e) {
e.printStackTrace();
}
}
#OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message from Server: " + message);
}
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("WebSocket Closed. Code:" + statusCode);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
}
public Client getBypassCertVerificationClient() {
Client client1 = null;
try {
// Create a HostnameVerifier that overrides the verify method to accept all hosts
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String host, SSLSession sslSession) {
return true;
}
};
// Create a TrustManager
TrustManager[] trust_mgr = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t) {
}
public void checkServerTrusted(X509Certificate[] certs, String t) {
}
}
};
// Create the SSL Context
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trust_mgr, new SecureRandom());
// Create the client with the new hostname verifier and SSL context
client1 = ClientBuilder.newBuilder()
.sslContext(sslContext)
.hostnameVerifier(hostnameVerifier)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return client1;
}
public String[] simple_Login_POST_request(String host, String user, String password, String resource, String data) {
String resp = null;
String[] headers = new String[2];
try {
// Create a Client instance that supports self-signed SSL certificates
Client client = getBypassCertVerificationClient();
// Create a WebTarget instance with host and resource
WebTarget target = client.target("https://" + host).path(resource);
// Build HTTP request invocation
Invocation.Builder invocationBuilder = target.request();
// Encode the user/password and add it to the request header
invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
Form form = new Form();
form.param("userid", user);
form.param("password", password);
// Invoke POST request and get response as String
//post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Response response = invocationBuilder.method("POST", Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
resp = (String) response.readEntity(String.class);
// Print input URL, input data, response code and response
System.out.println("URL: [POST] " + target.getUri().toString());
System.out.println("HTTP Status: " + response.getStatus());
System.out.println("HTTP Status: " + response.getHeaders());
headers[0] = response.getHeaderString("Set-Cookie");
//response.getStringHeaders()
headers[1] = response.getHeaderString("X-XSRF-TOKEN");
System.out.println("Response: \n" + resp);
response.close();
} catch (Exception e) {
e.printStackTrace();
}
return headers;
}
public static void main(String[] args) throws IOException {
String host = "";
String user = "";
String password = "";
String resource = "";
host ="192.168.122.1:8443";
user = "ADMIN";
password ="ADMIN";
websocketXXX wsNotification = new websocketxxx();
/////////////////////////////////////////////////////////////////
// Simple POST LOGIN Request
resource = "/api/login";
String headers[]= wsNotification.simple_Login_POST_request(host, user, password, resource, null);
////////////////////////////////////////////////////////////////
headers[0] = headers[0].substring(headers[0].lastIndexOf(",") + 1);
System.out.println("headers[0]: " + headers[0] + "\n");
String cookie = headers[0];
String XSRFToken = headers[1];
resource = "/status?-xsrf-=";
//wsNotification.simple_websocket_example(host, cookie, XSRFToken, resource);
wsNotification.run(host, cookie, XSRFToken, resource);
}
}
The implementation is mostly correct.
Setting raw Cookie and Sec-WebSocket-* headers is forbidden, you have to use the API.
Cookie handling from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("cookie",cookieVal);
To ClientUpgradeRequest.setCookies() :
ClientUpgradeRequest request = new ClientUpgradeRequest();
List<HttpCookie> cookies = new ArrayList<>();
cookies.add(new HttpCookie(...));
request.setCookies(cookies);
Note: if you are using the java CookieStore, then you can pass the CookieStore instance to the client as well, using the setCookiesFrom(CookieStore) method.
Sub Protocol Selection from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
To ClientUpgradeRequest.setSubProtocols():
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setSubProtocols("ao-json");

Using .NET to get results from an API

I wanted to use the Rapidshare API in my .NET app, but I am confused on how you send the request and bring back the result. Do you use Winsock or another method?
URLs are like this:
http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles_v1&files=288725357&filenames=my_upload.txt
Thanks.
Check out the System.Net namespace, specifically System.Net.WebClient.
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
Use the WebClient Class.
http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx
You can use this class to programatically interact with webpage. Here's some example code to log into a website. You can adapt this to interact with their web API:
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies;
string url = "http://www.jaxtr.com/user/login.jsp";
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer();
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StringBuilder sb = new StringBuilder();
StreamReader reader = new StreamReader(response.GetResponseStream());
while (!reader.EndOfStream)
{
sb.AppendLine(reader.ReadLine());
}
//Get the hidden value out of the form.
String fp = Regex.Match(sb.ToString(), "\"__fp\"\\svalue=\"(([A-Za-z0-9+/=]){4}){1,19}\"", RegexOptions.None).Value;
fp = fp.Substring(14);
fp = fp.Replace("\"", String.Empty);
cookies = request.CookieContainer;
//response.Close();
String requestString = "http://www.jaxtr.com/user/Login.action?tzOffset=6&navigateURL=&refPage=&jaxtrId=" + HttpUtility.UrlEncode(credentials.Username) + "&password=" + HttpUtility.UrlEncode(credentials.Password) + "&Login=Login&_sourcePage=%2Flogin.jsp&__fp="+HttpUtility.UrlEncode(fp);
request = (HttpWebRequest)WebRequest.Create(requestString);
request.CookieContainer = cookies; //added by myself
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response from login:" + response.StatusCode);
String messageText = (message.TruncateMessage && message.MessageText.Length > JaxtrSmsMessage.MAX_MESSAGE_LENGTH ? message.MessageText.Substring(JaxtrSmsMessage.MAX_MESSAGE_LENGTH) : message.MessageText);
String messageURL = "http://www.jaxtr.com/user/sendsms?CountryName=" + HttpUtility.UrlEncode(message.CountryName) + "&phone=" + HttpUtility.UrlEncode(message.DestinationPhoneNumber) + "&message=" + HttpUtility.UrlEncode(messageText) + "&bySMS=" + HttpUtility.UrlEncode(message.BySMS.ToString().ToLower());
request = (HttpWebRequest)WebRequest.Create(messageURL);
request.CookieContainer = cookies;
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response from send SMS command=" + response.StatusCode);
StringBuilder output = new StringBuilder();
using (Stream s = response.GetResponseStream())
{
StreamReader sr = new StreamReader(s);
while (!sr.EndOfStream)
{
output.AppendLine(sr.ReadLine());
}
}
response.Close();
}
else
{
Console.WriteLine("Client was unable to connect!");
}
}
catch (System.Exception e)
{
throw new SMSDeliveryException("Unable to deliver SMS message because "+e.Message, e);
}
This particular code logs into Jaxtr, a SMS messaging service, and sends an SMS message.