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();
Related
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.
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;
}
Hello every one i am a junior php developer i am working on converting java code to php.. on Java api hit and get response correctly and now i am trying to hit using curl http post in php this is my task in my software house plz help me
i am gonna show you my java code which is correctly working and then my php code which is not working and not parsing params to that api so pls kindly guide me
This is my Java Code
This is working correctly i want to do this same work from php
import java.io.*;
import java.util.jar.JarException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
class MyCode{
public static void main(String[] args) throws JarException, JSONException
{
testCustomerApiIsExposed();
}
public static void testCustomerApiIsExposed() throws JarException, JSONException {
try {
#SuppressWarnings("deprecation")
HttpClient c = new DefaultHttpClient();
HttpPost p = new
HttpPost("http://link");
String payload = "{id:\"" + 1 + "\"," + "method:\"" + "customerApi.getApiToken" + "\", params:[\"teabonezenminddemo1partner#gmail.com\", \"demo1234!\", \"\", \"\", \"\", \"\", \"\", false, \"\", \"\"" + "]}";
String mimeType="";
/*There is something here. What constructor are we really calling here? */
// p.setEntity(new StringEntity( payload,ContentType.create("application/json")));
p.setEntity(new StringEntity(payload));
HttpResponse r = c.execute(p);
BufferedReader reader = new BufferedReader(new InputStreamReader(r.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener("[" + builder.toString() + "]");
JSONArray finalResult = new JSONArray(tokener);
JSONObject o = finalResult.getJSONObject(0);
//Getting names of the JSON object here
System.out.println(o.names());
String apiToken = (String) o.get("result");
System.out.println(apiToken);
}
catch(IOException e) {
System.out.println(e);
}
}
}
now i am coding this on php but don't get response check it pls and guide me i am using curl http post and getApiToken method help me to sort out this problem i am very tense.
This is my php code
<?php
$data = array(params);
$ch = curl_init('http://link');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>
You are posting JSON from your java code. So use json here at PHP as well(make sure the format is ok):
$payload = "{params}";
And the curl options will be
// as you are posting JSON, so tell server that you are sending json
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
// Let server know that you are doing HTTP POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
Using these, I got sample response:
{"id":"1","result":"results"}
I am trying to use the graph API to upload a video to a users wall. The result is always an error response of "{"error":{"message":"(#352) Video file format is not supported","type":"OAuthException"}}". I have tried several different video types that are all supported based on this list, http://developers.facebook.com/docs/reference/api/video/. Based on my understanding of the documentation i have found, all that needs to be done is send a multipart form data request to "https://graph-video.facebook.com/me/videos" via a POST. BTW, I have been able to post a photo using similar techniques. The code i am using is below. It is based off of the PHP example at, http://developers.facebook.com/blog/post/493/. I have been able to upload the different videos using the facebook upload mechanism, so i know the videos are ok for Facebook. The access token is valid because i have used it to post a photo via the Graph API.
Any suggestions to what i am missing are welcome!
Here is the Java Code that i am using:
File video = new File(pathtovideofile);
DataInputStream dis = new DataInputStream(new FileInputStream(video));
byte[] bytes = new byte[(int)video.length()];
dis.read(bytes, 0, (int)video.length());
// set up the http client, the http method, and the multipart entity
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://graph-video.facebook.com/me/videos");
MultipartEntity mpEntity = new MultipartEntity( );
ContentBody cbVideo = new ByteArrayBody(bytes, "video/mp4", "Video Label");
ContentBody cbMessage = new StringBody( "New Video" );
ContentBody cbTitle = new StringBody( "Video Title" );
ContentBody cbAccessToken = new StringBody( accessTokenStr1 );
mpEntity.addPart( "access_token", cbAccessToken );
mpEntity.addPart( "file", cbVideo );
mpEntity.addPart( "description", cbMessage );
mpEntity.addPart( "title", cbTitle );
// put the multipart entity into the request
httppost.setEntity(mpEntity);
// send the request
HttpResponse response = httpclient.execute(httppost);
// get the response entity
HttpEntity resEntity = response.getEntity();
// read the stream and print out the results
InputStream instream = resEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String line;
StringBuilder responsestr = new StringBuilder();
while (( line = reader.readLine()) != null) {
responsestr.append(line);
}
System.out.println(responsestr.toString());
In php this worked for me. First upload the file to server and then try API call using Graph API.
$fbvideo_upload=move_uploaded_file($_FILES['attach_video']['tmp_name'],$fbvideo_path);
chmod($fbvideo_path,0777);
if($fbvideo_upload)
{
$args = array('message' => $status, "access_token" =>$accesstoken,"file"
=> '#'.$fbvideo_path, "title"=>$video_title, "description"=>$video_desc);
$post_url = "https://graph-video.facebook.com/me/videos?access_token=".$accesstoken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
$data=json_decode($data,true);
if(file_exists($fbvideo_path))
{
#unlink($fbvideo_path);
}
}
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>';
?>