How to use SocketChannel to connect to remote webserver - socketchannel

I am trying to get the response sent by the web server through Java NIO socketChannel. The read call of SocketChannel is not returning anything when it is in non-blocking
clientSocket.configureBlocking(false);
When specified true, means blocking mode, then it is returning response. Someone saying that we should use Selector when non-blocking mode enabled. But I didn't find a way to implement this.
FYI, Following is the code snippet I am trying.
public static void main(String[] args) throws IOException, InterruptedException
{
URL u = new URL("http://www.google.com");
InetSocketAddress addr = new InetSocketAddress("www.google.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET " + u.getFile() + " HTTP/1.0\r\n").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
clientSocket.read(readBuff);
while(clientSocket.read(readBuff) > 0)
{
System.out.println(new String(readBuff.array()).trim());
}
clientSocket.close();
}
Thanks in advance.

You should use loops to read() and write() till the buffer has no remaining bytes when non-blocking mode.

There two problems in your code:
the http request body is wrong. it needs additional "\r\n".
the readBuff need to cleared each time after reading.
below code is a working version:
static void working() throws Exception {
URL u = new URL("http://www.baidu.com");
InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET / HTTP/1.0\r\n\r\n").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
while (clientSocket.read(readBuff) != -1) {
System.out.println("Entring...");
System.out.println(new String(readBuff.array()).trim());
readBuff.clear();
}
clientSocket.close();
}
}
Notice, if it's http version 1.1, it will not break too. because it has a keeplive.

Related

How to make JSON PUT request through Codename one API

I'm not able top figure out JSON put request from codename one api. I didnt find any example to make this request.
Questions:
1. I'm not sure whether I have to send the content length parameter. If yes, how can I send that?
2. I have to send the request body with just "true" nothing else. There is no key and value to use req.addArgument() method.
3. Do I have to use buildRequestBody() method to override the request. Can you provide an example?
4. How to verify the result after receiving the response.
Any help can be appreciated.
Thanks.
Please find the code below.
req.setUrl(identityUrl );
req.setPost(false);
req.setHttpMethod("PUT");
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.addArgument("Content-Length", "4");
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
JSONParser parser = new JSONParser();
Map map2 = null;
try {
map2 = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(req.getResponseData()), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
If you want the content to be embedded wholly you need to override the buildRequestBody method. Notice that post needs to be true for the body to be called.
I don't think you need content-length:
req = new ConnectionRequest(identityUrl) {
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.getBytes("UTF-8"));
}
protected void readResponse(InputStream input) throws IOException {
map2 = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
}
protected void postResponse() {
// response completed, this is called on the EDT do the application logic here...
}
};
req.setPost(true);
req.setHttpMethod("PUT");
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
req.setDisposeOnCompletion(d);
NetworkManager.getInstance().addToQueue(req);
Notice that I no longer need to close streams or handle IOException as the connection request does everything for me. Also notice the read/build methods are called on the network threads and not on the EDT so you need to do the rest of the flow in the postResponse.

NullReferenceException during navigation from MainPage.xaml.cs to another xaml

My application takes username and password and on clinking the hyperlinkbutton, these values are sent to the server and hence server returns something like PASS:ClientID. I wish to navigate to SecondPage.xaml (from MainPage.xaml.cs) only if the responseString contains PASS.
Here is my code:
namespace aquila1
{
public partial class MainPage : PhoneApplicationPage
{
static string username;
static string password;
static string rs;
static NavigationService ns = new NavigationService();
// Constructor
public MainPage()
{
InitializeComponent();
}
private static ManualResetEvent allDone = new ManualResetEvent(true);
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
{
username = textbox1.Text;
password = textbox2.Text;
System.Diagnostics.Debug.WriteLine(username);
System.Diagnostics.Debug.WriteLine(password);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://60.243.245.181/fms_tracking/php/mobile_login.php?username=" + username + "&password=" + password);
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Console.WriteLine("Please enter the input data to be posted:");
string postData = username + "+" + password;
System.Diagnostics.Debug.WriteLine(postData);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
rs = responseString;
System.Diagnostics.Debug.WriteLine(responseString);
System.Diagnostics.Debug.WriteLine("#####");
System.Diagnostics.Debug.WriteLine(rs);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
move2();
allDone.Set();
}
private static void move2()
{
string[] rs1 = rs.Split(':');
if ((rs1[0].Trim()).Equals("PASS"))
{
ns.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));
}
else
{
MessageBox.Show(rs);
}
}
}
}
On running the code, i always get NullReferenceException .
Plz help me find the error and suggest corrections.
Thanks in advance
You're most likely getting the error because the NavigationService cannot find the resource /SecondPage.xaml. Is SecondPage located at the root of your project?
This can also be caused by trying to navigate before the target resource is loaded (for example, by navigating inside a page's constructor), but that doesn't immediately appear to be your problem.
This answer suggests that this problem can occur after changing namespaces or assembly names. It states that cleaning the project, ensuring all bin and obj folders are empty, then recompiling will fix it. However, its reference link is dead.

What does this socket error mean?

First of all thanks to everyone that answers questions on here. I have used this forum as a java bible. This is a homework problem and here is the assignment:
Write a program in Java that uses sockets to connect to a web server on port 80, requests a web page using GET of the HTTP protocol, and displays the resulting HTML
Not sure if I am doing this right or not. I have a very limited understanding of java. Most of this is from tutorials I have been going through. Any website links would be greatly appreciated.
Here is my error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from java.net.Socket to Socket
The method getInputStream() is undefined for the type Socket
Here is my code:
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws Exception
{
Server SERVER = new Server();
SERVER.run();
}
public void run() throws Exception
{
ServerSocket one = new ServerSocket(80);
//these are the two lines of code it is warning about
Socket myskt = one.accept();
InputStreamReader IR = new InputStreamReader(myskt.getInputStream());
//end of warnings
BufferedReader BR = new BufferedReader(IR);
String message = BR.readLine();
System.out.println(message);
if (message != null)
{
PrintStream PS = new PrintStream(System.out);
PS.println("Message Received");
}
URL website = new URL("www.dogs.com");
URLConnection yc = website.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in .readLine()) != null)
System.out.println(inputLine);
one.close();
}
// TODO Auto-generated method stub
}
The issue is that our code is not well-formed - you have a compilation error. My guess is that you have a class Socket in the same package as the class you're compiling, or a left-over class file (Socket.class) on the classpath. When the compiler runs, it uses the package local version of Socket, which is not the same type as java.net.Socket - hence the exception.
To resolve thisuse the fully qualified name java.net.Socket when declaring myskt

Getting response status code 0 in SmartGWT webservice call using json

I have developed application using SmartGWT. Now I need to call webservice using json to another application which is deployed in another server for submitting username and password. When I make a request with url and POST method, getting the response status code as 0 and response text as blank.
Here is my code,
public void sendRequest() throws Exception {
// Get login json data to be sent to server.
String strData = createLoginReqPacket();
String url = "some url";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/json");
builder.setHeader("Content-Length", strData.length() + "");
Request response = builder.sendRequest(strData, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
int statusCode = response.getStatusCode();
System.out.println("Response code ----"+response.getStatusCode()+"");
if (statusCode == Response.SC_OK) {
String responseBody = response.getText();
System.out.println("Respose :" + responseBody);
// do something with the response
} else {
GWT.log("Response error at server side ----",null);
// do in case of server error
}
}// end of method.
#Override
public void onError(Request request, Throwable exception) {
GWT.log("**** Error in service call ******",null);
}// end of method.
});
builder.send();
}// end of send request.
Please anybody knows the solution?
as i am new to GWT/SmartGwt i don't no much about it.
#ModeEngage
There is no reason to use GWT class(RequestBuilder), But i don't have any idea to use Data source. Can u give reference or stuffs to do this??
And when i run this in chrome browser i get the following in error console.
XMLHttpRequest cannot load http:// "requested Url" . Origin http:// "localhost:8888" is not allowed by Access-Control-Allow-Origin.
Any solutions???
I believe this is caused by Firewall. I've run some test, and this is the most likely explanation.

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.