How can I code a Bitcoin JSON-RPC "getwork" request in Java? I'm not entirely sure whether to ask this question on Bitcoin-SE or Stack Overflow, but I decided to post it here due to the direct relevancy of the question to Bitcoin and the general prominence of programming experience I have observed on Bitcoin-SE. If Bitcoin-SE is the incorrect place to post it, I apologize in advance; I'm new to SE and this was my best guess.

I'm attempting, in order to better understand how Bitcoin mining works, to code a simple Bitcoin CPU miner in Java, which I have some but not much experience with. All the online resources on JSON-RPC implementation in Java I have found have either been out of date and no longer functional or incomprehensible for someone with limited Java experience. How, in the most simplistic way possible, would I code a JSON-RPC getwork request (to a pool server) in Java and correctly parse the output into the variables required for mining?
The JSON-RPC protocol is very simple.  You POST to the mining pool (or the bitcoind client):

{"method": "getwork", "params": [], "id": "anything"}


and get back:

{"result": {"data": "hex bytes....", "target": "hex bytes...", ...}, ... }


You just need the first 80 bytes from result.data - you change the last 4 bytes (nonce) and compute the hashes.  Then, when you find a hash that is less than "target" (generally a hash with the high order 32 bits equal to zero), you call getwork again to report your hash (and earn a share in the pool):

{"method": "getwork", "params": ["hex-header"], "id": "anything"}


There a bunch on wonky byte-order encoding in the standard getwork call.  You'll generally want to reverse the bytes is each long integer (4 bytes) before hashing it, and do the same before reporting your found block back to the pool.  See the sample pyminer for a simple reference implementation of a miner (in python). Inside the Miner.work() function is where the magic happens. The work function takes two parameters: datastr, this is the value stored inside result.data and targetstr this is the value stored inside result.target.

One other thing - most pools require that you use Basic Authentication when you POST, so you'll need to include your username and password in the header of your request.