Why my Http request is done with `GET` instead of `POST`? - java

Why the code below do some GET request instead of POST resquest. I receive also CONTENT_TYPE: "" :(
HashMap<String, String> PostDataMap = new HashMap<>();
PostDataMap.put("method","any");
String PostDataString = HTTPEncodeParamNameValues(PostDataMap);
URL url = new URL(ApiServerURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setUseCaches(false);
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes(PostDataString);
dataOutputStream.flush();
dataOutputStream.close();
InputStream inputStream = url.openConnection().getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}

when you pass some user input to server that time used post and only getting data no user input that time used get.
when used get that time all data call in url. and it limited size. and also not secure.
when you used post that not go data into url. and is unlimited data to be send .and also secure.

Related

java getwork not fetching result

I have asked the same question in bitcoin stackexchange. Here I am re-posting it to reach a wider audience.
I was going through this post in stack exchange How can I code a Bitcoin JSON-RPC “getwork” request in Java?
I tried to write a simple snippet for just the getwork json rpc.
public static void main(String[] args) throws Exception {
String request = "{\"method\": \"getwork\", \"params\": [], \"id\":0}";
URL url = new URL("http://de01.supportxmr.com:7777");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn .getConnectTimeout() == 0)
conn.setConnectTimeout(1000);
if (conn.getReadTimeout() == 0)
conn.setReadTimeout(1000);
conn.setRequestMethod("POST");
String encoded = Base64.getEncoder().encodeToString(("<my_wallet_addr>:x").getBytes(StandardCharsets.UTF_8)); //Java 8
conn.setRequestProperty("Authorization", "Basic "+encoded);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(request.getBytes().length));
conn.setRequestProperty("X-Mining-Extensions", "midstate");
conn.setAllowUserInteraction(false);
conn.setUseCaches(false);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(request);
wr.close();
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[4096];
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String content = bos.toString();
is.close();
System.out.println(content);
}
when I run this code, I get an error
Exception in thread "main" java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:792)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:789)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1536)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at org.litecoinpool.miner.Test.main(Test.java:42)
What am I missing here? Is stratum proxy necessary to be running on the machine? If so how do I specify the parameters to run in the java code?
After changing the getwork to getblocktemplate / stratum as suggested, I tried a direct TCP connection also to the server.
public static void main(String[] args) throws Exception {
String message1 = "{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[]}";
String authorizemessage = "{\"params\": [\"<wallet_address>\", \"x\"], \"id\": 2, \"method\": \"mining.authorize\"}";
Socket soc = new Socket("de01.supportxmr.com", 7777);
System.out.println("connected");
OutputStream outputStream = soc.getOutputStream();
outputStream.write(authorizemessage.getBytes());
outputStream.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
JSONObject json = new JSONObject(in.readLine());
System.out.println("json response: " + json.toString());
outputStream.write(message1.getBytes());
outputStream.flush();
in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
json = new JSONObject(in.readLine());
System.out.println("json response: " + json.toString());
}
but no luck again :(

Receiving binary data over HTTP

I have a server which is sending a .png image to a client via a HTTP post request. The .png is stored inside a sqlite3 database, retrieved as a blob and this all works fine; I have tested saving the returned blob to disk and it can be opened as expected. When my client interprets the response, the payload has mysteriously grown in length from 16365 to 16367, inspecting the response string has shown there are some extra '?' characters intermittently in the stream
Testing the server using the ARC plug-in for Chrome has shown the response received there to be the right length, which leads me to believe there is a problem with my client code:
// request
URL url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(parameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.getOutputStream().write(parameters.getBytes());
// response
Reader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
for (int c; (c = rd.read()) >=0;)
sb.append((char)c);
String response = sb.toString();
// this String is of length 16367 when it should be 16365
Does anything jump out as being incorrect here? Note I am not doing any kind of character encoding on either side, should I be when using raw image data?
You can use DataInputStream to read the byte stream.
URL url = new URL("http://i.stack.imgur.com/ILTQq.png");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream dis = new DataInputStream(conn.getInputStream());
FileOutputStream fw = new FileOutputStream(new File("/tmp/img.png"));
byte buffer[] = new byte[1024];
int offset = 0;
int bytes;
while ((bytes = dis.read(buffer, offset, buffer.length)) > 0) {
fw.write(buffer, 0, bytes);
}
fw.close();
Alternatively an instance of BufferedImage can be created directly from the URL using ImageIO.read(java.net.URL).
URL url = new URL("http://i.stack.imgur.com/ILTQq.png");
BufferedImage image = ImageIO.read(url);

Download File with Http Request and UTF-8

I wrote a code like this.
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Cache-Control", "no-cache");
int responseCode = con.getResponseCode();
InputStream inputStream = con.getInputStream();
FileOutputStream outputStream = new FileOutputStream("C:\\aaaa\\ww.csv");
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
The code works well.I send request and ı can download the csv file into my computer.But ı want to know that if the csv file have turkish characters(ş,ğ,ı,ç) can ı download the csv with that characters.
or what can ı do for that characters to see them in csv file.
The server sends you a stream of bytes and you just save the byte stream on your disk, so you don't need to worry about characters.

Read Status code

conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.connect();
int code = conn.getResponseCode();
I have successfully established a connection. I am trying to pass the information over the internet.When the url is opened via browser I am getting response as
{"status":"0","responseCode":"1001","response":"Wrong Settings."}
For correct status is returned as 1.
Is there any method where I can get the status only.I have been trying the following methods but every time I am getting code (below is code snippet) as -1 irrespect of status code when I am verifying manually via browser
This is a JSON text. You will need to use a JSON library.
int code = conn.getResponseCode();
this method returns http status code, for http status codes see
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
while the response code you want to retrieve is actually the response string returned by the server.
To read this use:
try {
InputStream in = new BufferedInputStream(conn.getInputStream());
readStream(in);//method to read characters from stream.
finally {
urlConnection.disconnect();
}
}
You can add below code for get Response string from your connection.
OutputStream connectionOutput = null;
connectionOutput=connection.getOutputStream();
connectionOutput.write(requestJson.toString().getBytes());
connectionOutput.flush();
connectionOutput.close();
inputStream = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream dataCache = new ByteArrayOutputStream();
// Fully read data
byte[] buff = new byte[1024];
int len;
while ((len = inputStream.read(buff)) >= 0) {
dataCache.write(buff, 0, len);
}
// Close streams
dataCache.close();
Now get Response string of json like below.
String jsonString = new String(dataCache.toByteArray()).trim();
JSONObject mJsonobject=new JSONObject(jsonString);
You can now parse your key from this mJsonobject Object.

URL.openStream very slow

I'm downloading a picture on a android device from a SQL database; Everything works well, except that opening the Stream takes very long time (even if there is no picture to download). It takes approx 5 sec's before the actual download starts. Here is my code snippet:
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
//input = connection.getInputStream();
InputStream input = new BufferedInputStream(url.openStream());
File file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp" + "/testpic.jpg");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
//---blabla progressbar update etc..
The line InputStream input = new BufferedInputStream(url.openStream()); gives the problem. Any idea's on how to speed things up?
That's the point at which the actual TCP connection is created. It's a network problem, not a coding problem. Nothing you can do in the code to fix it.
I use this code to get a bitmap from a url. :)
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
try
{
byte[] bytes=new byte[1024];
for(;;)
{
int count=is.read(bytes, 0, 1024);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
os.close();
bitmap = decodeFile(f);
You're calling url.openStream() when creating the InputStream, but prior to that you're creating a new connection and calling connection.connect().
From the android JavaDoc: openStream() is "Equivalent to openConnection().getInputStream(types)"
http://developer.android.com/reference/java/net/URL.html#openStream()
In summary I think you should call connection.getInputStream() when initialising the InputStream.

Categories