Java GBK enconding and PHP - java

The following code is a PHP one I need to convert to Java to write it to a socket connection
$info = chr(6).chr(0).chr(255).chr(255).'info';
On PHP it works perfectly with this code
$Socket = fsockopen($this->Host, $this->Port, $errno, $errstr, 5);
fwrite($Socket, chr(6).chr(0).chr(255).chr(255).'info');
I tried doing this
public static void main(String[] args) {
char a = 6;
char b = 0;
char c = 255;
try {
Socket test = new Socket("shadowcores.twifysoft.net", 7171);
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(test.getOutputStream()));
write.write(Character.toString(a) + "." + Character.toString(b) + "." + Character.toString(c) + "." + Character.toString(c) + "." + "info");
BufferedReader read = new BufferedReader(new InputStreamReader(test.getInputStream()));
System.out.println(read.read());
test.close();
} catch (IOException e) {
e.printStackTrace();
}
}
With no success because I should be getting some information from the server after writing that message to it
How can I convert that PHP string to Java one?

Related

Java Random unicode character is appearing when using socket requesting

public final static String api = "api.hypixel.net";
public final static String toGet = "/skyblock/auctions";
public static void main(String[] args) {
try {
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(api, 443);
socket.setSoTimeout(500);
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("GET " + toGet + "?page=" + 1 + " HTTP/1.1");
pw.println("Host: " + api);
pw.println("");
pw.flush();
System.out.println("Wrote Socket: " + 1);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String e;
try {
while ((e = bufRead.readLine()) != null) {
sb.append(e);
}
} catch (SocketTimeoutException easports) {
//
}
System.out.println("finished write");
bufRead.close();
pw.close();
String[] splitted = sb.toString().split("\\{");
String copyofArr = String.join("{", Arrays.copyOfRange(splitted, 1, splitted.length));
String formatted = "{" + copyofArr.substring(0, copyofArr.length() - 1);
FileOutputStream fos = new FileOutputStream("gg1ay.txt");
fos.write(formatted.getBytes());
fos.flush();
fos.close();
JsonObject array = JsonParser.parseString(formatted).getAsJsonObject();
array.entrySet().forEach(entry -> System.out.println(entry.getKey() + " : " + entry.getValue()));
System.out.println("Got result: " + 1);
} catch (IOException e) {
System.err.println("an Exception");
e.printStackTrace();
}
}
When I request with this code, an weird alphabet comes with output (so i failed to parse json). it looks like unicode char, So I attached \u, now it shows weird chinese alphabet (like 耀, 翸, 磛). How can I fix this code?
I don't know why its working, but i fixed this problem with downgrading http version to 1.0.

Is it bad idea to use Socket on servlet?

I have Web Application server, which takes parameters and pass them to Client class. When calling the exactly same Client class in normal Java Application, everything works fine, but when calling the Client from servlet, the Client-Server conversation always hangs for either of two reasons:
Certain message (always the same one) sent from server is oddly formated and Client cannot process it.
If the message aforesaid is correctly formated, when the Client responds to it, the server never replies.
Here is the part of Client responsible for the connection:
int key;
int messCount=0;
int count=0;
ConnCrypto m = new ConnCrypto();
String[] s = {};
GameCrypto g = new GameCrypto(s);
int i = g.init();
Socket tcp;
BufferedReader reader;
BufferedWriter writer;
CryptHandler crypt= new CryptHandler();
static int err=0;
void setup() throws IOException {
tcp = new Socket(serverIp, serverPort);
InputStream InputStream = tcp.getInputStream();
OutputStream OutputStream = tcp.getOutputStream();
InputStreamReader InputStreamReader = new InputStreamReader(InputStream);
OutputStreamWriter OutputStreamWriter = new OutputStreamWriter(OutputStream);
reader = new BufferedReader(InputStreamReader);
writer = new BufferedWriter(OutputStreamWriter);
}
void send(String z) throws IOException {
System.out.println("Send:\t" + z);
z = m.encrypt(z);
writer.write(z);
writer.newLine();
writer.flush();
}
void crypt(String z) throws IOException {
System.out.println("Send:\t" + z);
z = crypt.crypt(z);
z = "d " + messCount + " "+(char)1 + z;
send(z);
messCount++;
}
void crypt2(String z) throws IOException {
z = g.encrypt(z);
z = "d " + messCount + " " + z;
send(z);
messCount++;
}
String recv() throws IOException {
char chr;
StringBuilder sb= new StringBuilder();
while((chr=(char)reader.read())!=0x0A)
sb.append(chr);
String str=sb.toString();
if (key != 0) {
str = m.decrypt(str);
int gg = str.charAt(0);
if (gg == 100) {
System.out.print("Raw:\t"+str);
str = "d " + crypt.decrypt(str.substring(5));
}
}
else if (str.charAt(0) == 99) {
key = Integer.parseInt(str.substring(5));
m.init(i, key);
}
System.out.println("Recv:\t" + str);
return str;
}
So is is it bad to use the Socket object, or is there something else in my code I should avoid?

proxy in java only showing 1 server reply

I have posted my java proxy code below.
It works but it only gives me 1 server response instead of everything.
After the 1 response I just get client sent packets but with a size of 0.
Screenshots also attached.
Any ideas?
I've done some debugging. If I remove everything in between
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
Which is from the reading server response code it works and I get the client packets. How come it doesn't work with server packets?
Code:
import java.io.*;
import javax.xml.bind.DatatypeConverter;
import java.net.*;
public class proxy{
public static void main(String[] args) throws IOException {
//PrintStream out = new PrintStream(new FileOutputStream("log.txt"));
//System.setOut(out);
try{
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(9339);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.out.println("Failed to start proxy" +e+ "");
}
}
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
System.out.println("Waiting for Client");
client = ss.accept();
System.out.println("Client Accepted!");
DataInputStream streamFromClient = new DataInputStream(client.getInputStream());
DataOutputStream streamToClient = new DataOutputStream(client.getOutputStream());
System.out.println("Connecting to server...");
// Make a connection to the real server.
server = new Socket("gamea.clashofclans.com", 9339);
System.out.println("Just connected client to " + server.getRemoteSocketAddress());
DataInputStream streamFromServer = new DataInputStream(server.getInputStream());
DataOutputStream streamToServer = new DataOutputStream(server.getOutputStream());
Thread t = new Thread() {
public void run() {
int bytesRead;
int type;
int size;
int version;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
type = streamFromClient.readUnsignedShort();
size = streamFromClient.readUnsignedShort();
size <<= 8;
size |= streamFromClient.readUnsignedByte();
version = streamFromClient.readUnsignedByte();
byte[] data = new byte[size];
streamFromClient.readFully(data, 0, size);
String FullHex = DatatypeConverter.printHexBinary(data);
System.out.println("Client sending data to server:");
System.out.println("Type: " + type + "");
System.out.println("Data Size: " + size + "");
System.out.println("Version: " + version + "");
System.out.println("Full Data: " + FullHex + "");
System.out.println("\n\n");
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
t.start();
int bytesRea;
int typ;
int siz;
try {
while ((bytesRea = streamFromServer.read(reply)) != -1) {
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
streamToClient.write(reply, 0, bytesRea);
streamToClient.flush();
}
} catch (IOException e) {
}
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
This doesn't make sense. You're reading up to 4096 bytes from the server and then reading two type bytes and three length bytes and what you think is the request data, and writing what you read originally. So you're consuming the data about twice.
This can't work. You need to either just read the type, length, and value, and write them out again, or else, much more simply, just copy bytes from the input to the output, in both directions. (That way of course you can't do logging.)
NB Don't ignore IOExceptions, and especially not EOFExceptions when reading from DataInputStreams (or ObjectInputStreams).

Java String Index Out of Range in Proxy

Hey Guys my following code is a proxy written in java.
Everytime I try to run it, it throws an String Index out of range:-1 exception, which I don't know how to handle.
I also nee to redirect the request to a specific webpage, if a "bad" word has been written in the URL or the content of the web page.
How do I do that?
Please Help me!
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ProxyServer{
//Create the Port the user wants the proxy to be on
static Scanner sc = new Scanner(System.in);
public static final int portNumber = sc.nextInt();
public static void main(String[] args) {
ProxyServer proxyServer = new ProxyServer();
proxyServer.start();
}
public void start() {
System.out.println("Starting the SimpleProxyServer ...");
try {
//bad list of words
String bad[]= new String[4];
bad[0]= "SpongeBob";
bad[1]= "Britney Spears";
bad[2]= "Norrköping";
bad[3]= "Paris Hilton";
ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);// this is the socket of the proxy
System.out.println(serverSocket);
byte[] buffer= new byte [10000] ;
//
while (true) {
Socket clientSocket = serverSocket.accept(); // the client willl be the socket the proxy "accepts"
boolean badContent =false; //flag, if the input contains one of the bad words
InputStream inputstream = clientSocket.getInputStream(); // retreiving request from the client
int n = inputstream.read(buffer); //reading buffer and storing its size
String browserRequest= new String(buffer,0,n+1); //new String(buffer,0,n);
String realbrowserRequest =( browserRequest+"Connection close()");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
for (int j=0; j<bad.length;j++){ //checking of the URL contains the bad words
if(realbrowserRequest.contains(bad[j])){
badContent =true; // if yes the flag will be set to true
}
}
//if(badContent == true){
//System.out.println("bad detected");
// try
// {
// URL url = new URL( "http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html" );
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader( url.openStream() ) );
//
// String s;
//
// while ( ( s = in.readLine() ) != null )
// System.out.println( s );
//
// in.close();
// }
// catch ( MalformedURLException e ) {
// System.out.println( "MalformedURLException: " + e );
// }
// catch ( IOException e ) {
// System.out.println( "IOException: " + e );
// }
// else{
System.out.println("Das ist der Browserrequest: \n"+realbrowserRequest);
System.out.println("Das ist der Erste Abschnitt");
int start = browserRequest.indexOf(("Host: ") + 6);
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end-1 ); //retreiving host
if(badContent =true) //if the URL already contains inappropriate material
{
URL url = new URL( "http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html" );
host = url.getHost(); // set the host to the given one
}
System.out.println("Connecting to host " + host);
Socket hostSocket = new Socket(host, 80); //I can change the host over here
OutputStream HostOutputStream = hostSocket.getOutputStream();
// PrintWriter writer= new PrintWriter (HostOutputStream);
// writer.println();
System.out.println("Forwarding request to server");
HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
HostOutputStream.flush();
InputStream HostInputstream = hostSocket.getInputStream();
OutputStream ClientGetOutput = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = HostInputstream.read(buffer);
String vomHost = new String(buffer,0,n);
System.out.println("\nVom Host\n\n"+vomHost);
for(int i=0;i<bad.length;i++){
if(vomHost.contains(bad[i])){
badContent=true;
}
}
System.out.println("Receiving " + n + " bytes");
if (n > 0) { // && badContent == false
ClientGetOutput.write(buffer, 0, n);
}
} while (n>0 && badContent == false); //n>0&& badContent == false
if (badContent == true){
}
ClientGetOutput.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The issue is here :
int start = browserRequest.indexOf(("Host: ") + 6);
This means you are doing this :
int start = browserRequest.indexOf("Host: 6");
6 is being concatenated to "Host : "
Try this :
int start = browserRequest.indexOf("Host: ") + 6;
There are many issues in your code:
1) Change the line :
int start = browserRequest.indexOf(("Host: ") + 6);
To:
int start = browserRequest.indexOf("Host:") + 6;
As mentioned in ToYonos's answer, becuase it is wrong.
2) You have to make sure that the two variables start and end are not equal to -1(if they doesn't exist in browserRequest):
if(end>start && start>0)
{
String host = browserRequest.substring(start, end-1 );
}
This will avoid many Exceptions.

Sockets: Simple POST request not working

I am trying to make a post request on this page http://www2.gcitrading.com/quotes/converter.asp,
but its not working..I still get the same page after my post request (without the result).
When I use the browser, after I click convert the page turns to http://www2.gcitrading.com/quotes/converter.asp?lang= Im really confused with this one. How can I make this work?
Here is my code:
public static void main(String[] args) {
Socket sock = new Socket();
InputStream in;
OutputStream out;
byte[] readBuffer = new byte[4096];
String res = "";
try {
sock.connect(new InetSocketAddress("www2.gcitrading.com", 80));
in = sock.getInputStream();
out = sock.getOutputStream();
out.write(new String("GET /quotes/converter.asp HTTP/1.1\r\n").getBytes());
out.write(new String("Host: www2.gcitrading.com\r\n\r\n").getBytes());
while(true) {
int readSize = in.read(readBuffer);
if(readSize < 1)
break;
res += new String(readBuffer, 0, readSize);
if(res.contains("</html>"))
break;
}
String cookie = res.substring(res.indexOf("kie:") + 5,res.indexOf("path=/")+6);
System.out.println("SHow cookie - " + cookie);
String convert_this = URLEncoder.encode("form_amount=1&form_from_currency=DZD&form_to_currency=USD", "UTF-8");
out.write(new String("POST /quotes/converter.asp?lang= HTTP/1.1\r\n").getBytes());
out.write(new String("Host: www2.gcitrading.com\r\n").getBytes());
out.write(new String("Content-Length: " + convert_this.length() + "\r\n").getBytes());
out.write(new String("Content-Type: application/x-www-form-urlencoded\r\n").getBytes());
out.write(new String("Cookie: " + cookie +"\r\n").getBytes());
out.write(new String("\r\n").getBytes());
out.write(convert_this.getBytes());
readBuffer = new byte[4096];
res = "";
while(true) {
int readSize = in.read(readBuffer);
if(readSize < 1)
break;
res += new String(readBuffer, 0, readSize);
if(res.contains("</html>"))
break;
}
System.out.println(res);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks. Btw, I need to achieve this using c/c++ sockets, but I tested it using java first.
I try this it's work
String convert_this = URLEncoder.encode("form_amount", "UTF-8")+ "=" + URLEncoder.encode("1", "UTF-8");
convert_this += "&" + URLEncoder.encode("form_from_currency", "UTF-8")+ "=" + URLEncoder.encode("DZD", "UTF-8");
convert_this += "&" + URLEncoder.encode("form_to_currency", "UTF-8")+ "=" + URLEncoder.encode("USD", "UTF-8");
Try something like this:
DataOutputStream dataOut = new DataOutputStream(sock.getOutputStream());
dataOut.writeUTF("[Your String here]");
Also, you should be using the higher-level URL, not sockets.
It's solved. I used Charles, it's a web debugging tool, and found out that my post request is lacking. I simply added in my post request : convert_it=true

Categories

Resources