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
Related
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.
I have many images in a folder, and I want to upload this files, in that folder, to a php server, in java using httpurlconnection.
Until now, I made it but just with one photo, like the code I show you down.
public class SendImage {
private final String CrLf = "\r\n";
public static void main(String[] args) {
SendImage image = new SendImage();
image.httpConn();
}
private void httpConn(){
URLConnection lig = null;
OutputStream os = null;
InputStream is = null;
try{
String urlParameters = "subPasta=sandro&nomepc=Sandro-PC&printPasta=Printscreens";;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL("http://192.168.0.105/dashboard3/uploadImg.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
System.out.println("url: "+ url);
lig = url.openConnection();
lig.setDoOutput(true);
FileInputStream imgIs = new FileInputStream(new File("C:\\Users\\Sandro\\workspace\\testeLogin\\screenshot\\2017_3_16_3_59.png"));
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.png\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
lig.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
lig.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = lig.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = lig.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
}
But I want send all photos in that folder
if you can, show me the code in php too please.
I have roughly tried to parse the JSON from Google Distance Matrix API, but it is not showing the distance.
My GPS location is not 0,0 that I'm sure of.
String distance = getMatrix(latitude,longitude);
My code for the function is:
private String getMatrix(double lat , double lang){
JSONObject jObj;
String getdistance = "";
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
String data = "";
InputStream reader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
urlConnection.disconnect();
} catch(Exception e) {
} finally {
}
try {
jObj = new JSONObject(data);
JSONArray rowsArray = jObj.getJSONArray("rows");
JSONObject rows = rowsArray.getJSONObject(0);
JSONArray elementsArray = rows.getJSONArray("elements");
JSONObject newDisTimeOb = elementsArray.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
getdistance = distOb.optString("text").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return getdistance;
}
First, check if you've correctly build the url string in the code:
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
// Line to check if url code is right
Log.d("APP", "strUrl = " + strUrl);
Then check your following code, whether it really produce the data:
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
My suggestion is to use BufferedReader instead reading the response byte per byte.
Then change:
getdistance = distOb.optString("text").toString();
to
getdistance = distOb.getString("text");
Because you don't need to convert to string again here.
I've search Client Libraries for Google Maps Web Services and found DistanceMatrixApi.java. Maybe we can use it, but I can't assure of it.
I'm using the code below to read a Unix socket:
Boolean flag = false;
while (!flag) {
try {
File socketFile = new File("./RISP");
AFUNIXSocket sock = AFUNIXSocket.newInstance();
sock.connect(new AFUNIXSocketAddress(socketFile));
System.out.println("!!!!!!!!!!CONNECTED!!!!!!!!!");
flag = true;
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line = null;
while ((line = input.readLine())!=null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("NOT CONNECTED....." + e);
}
try {
Thread.sleep(2000);
} catch (InterruptedException inter) {
System.out.println(inter);
}
}
I need to read the first 4 bytes of each pack and convert them from binary to integer.
I've read many posts but I'm still looking for the best solution to my problem.
Reader and Writer are designed for reading text.
For binary, you should try InputStream and OutputStream, in this case, you want DataInputStream, possibly buffered.
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
int len = in.readInt(); // read big-endian.
if (LITTLE_ENDIAN)
len = Integer.reverseBytes(len);
byte[] bytes = new byte[len];
in.readFully(bytes);
seems it works
DataInputStream in = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
int len = -1;
while ((len = in.readInt()) != -1) {
len = Integer.reverseBytes(len);
byte[] bytes = new byte[len];
in.readFully(bytes);
if (bytes.length > 4) {
System.out.println(" BYTE0: " + bytes[0] +
" BYTE1: " + bytes[1] +
" BYTE2: " + bytes[2] +
" BYTE2: " + bytes[3] +
" LENGHT: " + bytes.length);
}
}
please let me know is i miss something.
thanks a lot to you guys.
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?