java getwork not fetching result - java

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 :(

Related

Calling Post request without body in java

I have a post API which doesn't accept any input. I have to get output from API. But it is giving compilation error.
HttpURLConnection connection = null;
String targetUrl="https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1/bots/"+BotID+"/dynamicEntities/"+dynamicEntityId+"/pushRequests
URL url = new URL(targetUrl);
connection=(HttpURLConnection) url.openConnection();
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2");
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
**osw.write();** //this line is expecting input in parameter
osw.flush();
osw.close();
os.close();
connection.connect();
If I dont pass any value in osw.write() it gives compilation error. How can I resolve the same.
Look at the following method for the post call. You will need to add the outputstream to the osw.write() as it expects a parameter.
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
else {
System.out.println("POST request not worked");
}
}
For more details on the above code look here.

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

Rest Api to Decrypt GZIP Body

An API is sending a large amount of data in the body in form of GZIP, I need to create rest API to decrypt and save it in the database, but I am not able to decrypt the data.
`#GetMapping
public void hello() throws IOException {
String payload = "{\n" +
" \"name1\": \"shrikant\",\n" +
" \"date\": \"Fri Apr 05 15:48:59 IST 2019\"\n" +
"}";
String urlStr = "http://localhost:8080/hello";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(60000);
conn.setConnectTimeout(60000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Content-Encoding", "gzip");
OutputStream os = conn.getOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(payload.getBytes(StandardCharsets.UTF_8));
System.out.println("payload " +
Arrays.toString(payload.getBytes(StandardCharsets.UTF_8)));
os.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
}`
API to receive the data.
#PostMapping("hello")
public byte[] hello1(HttpServletRequest request) throws IOException {
System.out.println("hi");
ByteArrayInputStream bis = new ByteArrayInputStream();
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
}
but not able to decrypt data.
how to decrypt request.
On the client side you should close GZIPOutputStream before closing OutputStream.
gos.close();
os.close();
On the server side you should use InputStream from request
ServletInputStream inputStream = request.getInputStream();
GZIPInputStream gis = new GZIPInputStream(inputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
For streams better use try-with-resources blok you won't have to remember about closing streams.
try (OutputStream os = conn.getOutputStream()) {
try (GZIPOutputStream gos = new GZIPOutputStream(os)) {
gos.write(payload.getBytes(StandardCharsets.UTF_8));
}
}

Send JSON data through POST in Java

I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.

HttpURLConnection : Unable to retrieve the correct error message

I am calling REST service using java HttpURLConnection object.
When the HTTP server returns any business error, I am not able to retrieve the error properly.
For example, when I call the REST service through SoapUI, I get below error
<exception>
<errors>
<error>
<diagnostic>Matching item with shortCode = 1089992001234 found</diagnostic>
<field>shortCode</field>
<message>The Shortcode/CSG combination must be unique.</message>
<objectFailingValidationClass>com.axiossystems.assyst.dto.organisationConfiguration.SectionDto</objectFailingValidationClass>
<rule>isUniqueShortCodeWithCSG</rule>
</error>
</errors>
<message>A complex validation error has been detected by the application.</message>
<type>ComplexValidationException</type>
</exception>
But in the java code I getting below error, the request message format is correct
java.io.IOException: Server returned HTTP response code: 400 for URL: https://it-test.ihc.eu/assystREST/v2/sections
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1676)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1672)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at RestCaller.execute(RestCaller.java:59)
at RestCaller.main(RestCaller.java:18)
Can anyone let me know how to capture business error returned form server? Like the one received in SoapUI
Below is my code
try
{
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("accept", "application/xml");
String userpassword = username + ":" + password;
String authStringEnc = new String(Base64.encodeBase64(userpassword.getBytes()));
connection.setRequestProperty("Authorization", "Basic "+authStringEnc);
if (HttpMethod == "POST")
{
connection.setRequestMethod("POST");
//connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Type", "application/xml");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(payLoad);
writer.flush();
writer.close();
os.close();
}
int statusCode = connection.getResponseCode();
System.out.println("--------000----------" + statusCode);
InputStream is = connection.getInputStream();
System.out.println("--------111----------");
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
System.out.println("--------222----------");
String line;
System.out.println("--------333----------");
StringBuffer response = new StringBuffer();
System.out.println("--------444----------");
while ((line = rd.readLine()) != null)
{
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch (Exception e)
{
System.out.println("--------exception----------");
e.printStackTrace();
return "";
}
In case of error (i.e., httpStatusCode other than 200), you might have to read errorStream of HttpUrlConnection as below. After you read errorMessage, you could to deserialize it to the DTO that matches the xml output you pasted. Please note readErrorString() below is incomplete and expect you to use it for reference only
if (statusCode != 200) {
InputStream errorStream = connection.getErrorStream();
String errorMessage = (errorStream != null) ? readErrorString(errorStream) : connection
.getResponseMessage();
}
private void readErrorString(InputStream is) {
String responseString = null;
BufferedInputStream bis = null;
try {
StringBuilder sb = new StringBuilder();
bis = new BufferedInputStream(inputStream);
byte[] byteContents = new byte[4096];
int bytesRead;
String strContents;
while ((bytesRead = bis.read(byteContents)) != -1) {
strContents = new String(byteContents, 0, bytesRead, "UTF-8"); // You might need to replace the charSet as per the responseEncoding returned by httpurlconnection above
sb.append(strContents);
}
responseString = sb.toString();
} finally {
if (bis != null) {
bis.close();
}
}
}
return responseString;
400 error means your response data is malformed, means not in correct format. Please check again with your response api.

Categories