Hit Api and get Response using http post and curl - java

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"}

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.

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;
}

HTTP POST request with JSON object as data

I am struggling to make an HTTP POST request with JSON object as data.
As you can see below, first I created an HTTP Post request. Then I commented out part of it and attempted to modify it in order to add JSON related code. One of the things that confused me was that despite seeing a number of tutorials using the import "org.json.simple.JSONObject" my IDE reads an error message and states "the import org.json.simple.JSONObject cannot be resolved".
Any advice about how to make this code work would be much appreciated.
import java.io.*;
import java.net.*;
import org.json.simple.JSONObject;
public class HTTPPostRequestWithSocket {
public void sendRequest(){
try {
JSONObject obj = new JSONObject();
obj.put("instructorName", "Smith");
obj.put("courseName", "Biology 101");
obj.put("studentName1", "John Doe");
obj.put("studentNumber", new Integer(100));
obj.put("assignment1", "Test 1");
obj.put("gradeAssignment1", new Double("95.3"));
/*
//Note that this code was taken out in order to attempt to send
//the information in the form of JSON.
String params = URLEncoder.encode("param1", "UTF-8")
+ "=" + URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8")
+ "=" + URLEncoder.encode("value2", "UTF-8");
*/
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("POST "+path+" HTTP/1.0rn");
wr.write("Content-Length: "+obj.length()+"rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(obj);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close();//Should this be closed at this point?
}catch (Exception e) {e.printStackTrace();}
}
}
The reason your IDE says it cannot resolve the import org.json.simple.JSONObject is because the org.json.simple.* packages and classes are not included in Java, but rather belong to the JSON Simple library.
I think that uses Socket is not a good idea. You can better use:
http://hc.apache.org/httpcomponents-client-ga/ (A HTTP Client)
or a java.net.URLConnection. Example:
http://crunchify.com/create-very-simple-jersey-rest-service-and-send-json-data-from-java-client/
You need the jar with the org.json.simple.JSONObject implementation:
http://www.java2s.com/Code/Jar/j/Downloadjsonsimple11jar.htm

Always get video format not supported when posting a video

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);
}
}

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