Java URLConnection to php - java

How to write this code in php?
What i should use? CURL? fsockopen ? and what is actually send to server (outputString is a post / get and what its variable name)?
URL url = new URL(targetURL);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/xml");
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
out.write(outputString.getBytes("UTF-8"));
out.close();
conn.connect();
final int code = conn.getResponseCode();
final String contentType = conn.getContentType();
final StringBuffer responseText = new StringBuffer();
InputStreamReader in = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] msg = new char[2048];
int len;
while ((len = in.read(msg)) > 0) {
responseText.append(msg, 0, len);
}
Thank you for any answer.

This is a basic example of a cURL post...
Further reading at http://www.php.net/manual/en/function.curl-exec.php has very good examples too.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.site.com/test.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"var1=value1&var2=value2&var3=value3");
// Get server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($result == "OK") { ... } else { ... }
?>
An example for SENDING XML:
<?php
/**
* Define POST URL and also payload
*/
define('XML_PAYLOAD', '<?xml version="1.0"?><member><name>name</name></member>');
define('XML_POST_URL', 'http://www.domain.com/build_xml.php');
/**
* Initialize handle and set options
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
/**
* Execute the request and also time the transaction
*/
$start = array_sum(explode(' ', microtime()));
$result = curl_exec($ch);
$stop = array_sum(explode(' ', microtime()));
$totalTime = $stop - $start;
/**
* Check for errors
*/
if ( curl_errno($ch) ) {
$result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
} else {
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
switch($returnCode){
case 404:
$result = 'ERROR -> 404 Not Found';
break;
default:
break;
}
}
/**
* Close the handle
*/
curl_close($ch);
/**
* Output the results and time
*/
echo 'Total time for request: ' . $totalTime . "\n";
echo $result;
/**
* Exit the script
*/
exit(0);
?>
And a 3rd for good measure, just to illustrate an alternative approach;
<?php
$xml = '<request>Testing</request>';
$server = '...'; // URL to server.php
$options = array
(
CURLOPT_URL => $server,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $xml,
CURLOPT_RETURNTRANSFER => true
);
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
echo '<pre>', htmlspecialchars($response), '</pre>';
?>

Related

Convert PHP curl request to Java

So I have this PHP code which makes a POST request to the specified URL. The $data array acts as a filter to apply to the request (for example to display the second page and maximum 10 items for that page). By default that values are "currentPage => 1" and "itemsPerPage => 100" (I'm accessing an API).
<?php
$usercode = '';
$username = '';
$password = '';
$URL = '';
$data =
array (
'currentPage' => 2,
'itemsPerPage' => 10
);
$hash = sha1(http_build_query($data) . sha1($password));
$requestData = array(
'code' => $usercode,
'username' => $username,
'data' => $data,
'hash' => $hash);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));
$result = curl_exec($ch);
$json_pretty = json_encode(json_decode($result), JSON_PRETTY_PRINT);
echo $json_pretty;
It works exactly as intended using PHP language, but I want to achieve the same behaviour in Java. The problem is that the filters doesn't apply (for every request the values of filters are ignored and the default values are used). I tried to make the request in the same form as in PHP, but for some reason the filters doesn't apply. This is my attempt using Apache's HttpClient:
public class Foo
{
private static String httpBuildQuery(List<? extends NameValuePair> parameters) {
return URLEncodedUtils.format(parameters, "UTF-8").replace("*", "%2A");
}
public static void main(String[] args)
{
String username = "";
String password = "";
String usercode = "";
final String URL = "";
String headerValueToBeEncoded = username + ":" + password;
String encodedHeaderValue = Base64.getEncoder().encodeToString(headerValueToBeEncoded.getBytes());
List<NameValuePair> data = new ArrayList<>();
data.add(new BasicNameValuePair("currentPage", "2"));
data.add(new BasicNameValuePair("itemsPerPage", "10"));
String passwordHash = DigestUtils.sha1Hex(password);
String dataQueryString = Foo.httpBuildQuery(data);
String valueToBeHashed = dataQueryString + passwordHash;
String hash = DigestUtils.sha1Hex(valueToBeHashed);
List<NameValuePair> requestData = new ArrayList<>();
requestData.add(new BasicNameValuePair("code", usercode));
requestData.add(new BasicNameValuePair("username", username));
requestData.add(new BasicNameValuePair("data", data.toString()));
requestData.add(new BasicNameValuePair("hash", hash));
String requestDataQueryString = Foo.httpBuildQuery(requestData);
try (CloseableHttpClient client = HttpClientBuilder.create().build())
{
HttpPost request = new HttpPost(URL);
request.setHeader("Authorization", "Basic " + encodedHeaderValue);
request.setEntity(new StringEntity(requestDataQueryString));
HttpResponse response = client.execute(request);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufReader.readLine()) != null)
{
builder.append(line);
builder.append(System.lineSeparator());
}
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i=0; i < jsonArray.length(); i++)
{
System.out.println(jsonArray.getJSONObject(i).get("id"));
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The values of predefined that predefined strings (username, password, etc) have been left empty here because they contain sensitive information. In the last part I have printed only the values of the id's to check if the filters have been applied, but for every request the it prints 100 id's.

how can i convert from php curl to java

I am looking to try convert curl to JAVA code. cURL code in php work perfect but in java theres porblem this is code php
$urlt="http://api.xxxxxxx/xxxxx";
$apikey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$camp="id";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$urlt);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('apikey' => $apikey, 'apif' => 'ge', 'camp' => $camp));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
and this is my convert to java
String apikey="xxxxxxx";
String camp="17";
URL url = new URL("http://xxxxxxx/xxxxxxxx");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(true);
String postData = "apikey"+apikey+"apif=ge"+"camp"+camp; // I need somthing like this
con.setRequestProperty("Content-length", String.valueOf(postData.length()));
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ( (c = input.read()) != -1) {
resultBuf.append((char) c);
}
input.close();
return resultBuf.toString();
and this is the out put
Response (Code):200
Response (Message):OK
API KEY REQUIRED
You're not encoding your parameters correctly. You're missing an = and the & separators:
"apikey="+apikey+"&apif=ge"+"&camp="+camp
If there's a way of having the library do the encoding for you, as you do in the CURL example using an array(...), that's usually a lot safer.

Converting HTTP POST from curl (PHP) to HttpURLConnection (Java)

I tried to convert the below PHP code (taken from https://www.cryptocoincharts.info/tools/api) to java
// define pairs
$post = array("pairs" => "ltc_usd,ppc_btc");
// fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://api.cryptocoincharts.info/tradingPairs");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
$rawData = curl_exec($curl);
curl_close($curl);
// decode to array
$data = json_decode($rawData);
// show data
echo "<pre>";
foreach ($data as $row)
{
echo "Price of ".$row->id.": ".$row->price."\n";
echo "Trade this pair on ".$row->best_market."\n";
}
echo "</pre>";
Java Code
URL url = new URL("http://api.cryptocoincharts.info/tradingPairs");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// CURLOPT_POST
con.setRequestMethod("POST");
// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);
String postData = "ltc_usd,ppc_btc";
con.setRequestProperty("Content-length", String.valueOf(postData.length()));
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();
// "Post data send ... waiting for reply");
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());
// read the response
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ( (c = input.read()) != -1) {
resultBuf.append((char) c);
}
input.close();
System.out.println("resultBuf.toString() " + resultBuf.toString());
As per the API, after converting this to java I should get only the details of LTC and PPC details. Instead I am getting a strange Json with all trading pairs.
2 $post = array("pairs" => "ltc_usd,ppc_btc"); Posted the PHP code as I am not known the exact equivalent in Java
Could you please point out if my conversion from PHP to Java is correct ?
As far as I see, the main difference between the two implementation is related to the $post variable.
In the PHP implementation $post is a key/value array but in Java I only see the value part.
I suggest to change the postData variable content into pairs=ltc_usd,ppc_btc
You didn't mentioned key part, only value is mentioned. And when we fetch data from PHP API, we have an associative array. If u want to display the output, u need to know the key and value of the particular associative array.
And the InputStream and OutputStream should be inside try-resources
you can try curl-to-java lib to convert curl php code to java code
https://github.com/jeffreyning/curl-to-java
demo like this
public Object curl(String url, Object postData, String method) {
CurlLib curl = CurlFactory.getInstance("default");
ch = curl.curl_init();
curl.curl_setopt(ch, CurlOption.CURLOPT_CONNECTTIMEOUT, 1000);
curl.curl_setopt(ch, CurlOption.CURLOPT_TIMEOUT, 5000);
curl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYPEER, false);
curl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYHOST, false);
String postDataStr = "key1=v1";
curl.curl_setopt(ch, CurlOption.CURLOPT_CUSTOMREQUEST, "POST");
curl.curl_setopt(ch, CurlOption.CURLOPT_POSTFIELDS, postDataStr);
curl.curl_setopt(ch, CurlOption.CURLOPT_URL, "https://xxxx.com/yyy");
Object html = curl.curl_exec(ch);
Object httpCode = curl.curl_getinfo(ch, CurlInfo.CURLINFO_HTTP_CODE);
if (httpCode != null && 200 == Integer.valueOf(httpCode.toString())) {
return null;
}
return html;
}

What will be the equivalent to following curl command in java

i need to convert the following curl command into java command.
$curl_handle = curl_init ();
curl_setopt ($curl_handle, CURLOPT_URL,$url);`enter code here`
curl_setopt ($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($curl_handle, CURLOPT_POST, 1);
curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $postfields);
//echo $postfields;
$curl_result = curl_exec ($curl_handle) or die ("There has been a CURL_EXEC error");
Http(s)UrlConnection may be your weapon of choice:
public String sendData() throws IOException {
// curl_init and url
URL url = new URL("http://some.host.com/somewhere/to/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// CURLOPT_POST
con.setRequestMethod("POST");
// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);
String postData = "my_data_for_posting";
con.setRequestProperty("Content-length", String.valueOf(postData.length()));
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();
// "Post data send ... waiting for reply");
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());
// read the response
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ( (c = input.read()) != -1) {
resultBuf.append((char) c);
}
input.close();
return resultBuf.toString();
}
I'm not quite sure about the HTTPS_VERIFYPEER-thing, but this may give you a starting point.
Have a look at the java.net.URL and java.net.URLConnection libraries.
URL url = new URL("yourUrl.com");
Then use a an InputStreamReader & BufferedReader.
More information in Oracles example: http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
This might also help: How to use cURL in Java?

Java HTTP Post Raw Data

I'm looking to make an HTTP post request given the raw data that I have. I've spent a while looking for the solution, made a handful of attempts and I'm looking for a little bit of help. The PHP code for what I'm looking to do looks like this:
<?
$url="http://localhost:3000";
$postdata="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<hi></hi>";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
echo($result);
?>
My attempt was this:
private String setXmlPostHeader(Document doc, PostMethod postMethod) throws java.io.IOException, java.io.UnsupportedEncodingException,
javax.xml.transform.TransformerException
{
ByteArrayOutputStream xmlBytes = new ByteArrayOutputStream();
XML.serialize( doc, xmlBytes );
final byte[] ba = xmlBytes.toByteArray();
String data = new String(ba, "utf-8");
InputStreamRequestEntity re = new InputStreamRequestEntity(new ByteArrayInputStream(ba));
postMethod.setRequestEntity(re);
postMethod.setRequestHeader("Content-type", MediaType.XML.toString() + "; charset=UTF-8");
return data;
}
And then executing the postMethod, but this simply is a post containing no data. Does anyone see anything wrong that I'm doing? I'd like to figure out how to change this method to make it actually work. Thanks!
-Ken
Wouldn't the java.net.URLConnection class work better?
It doesnt look like you are calling:
int result = httpclient.executeMethod(postMethod);
postMethod.releaseConnection();

Categories

Resources