I am using the curl command below to get access token from instagram api after getting authorization code.
curl \-F 'client_id=cf07d1a2c69940e59420b6db4c936f4a' \
-F 'client_secret=fb0a975ca2024a1592459308df5ead47' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=http://localhost:8080/Insta_SMI_M1/accessToken/' \
-F 'code=fcf66e5f09bf43a18ab15e5f1e0ae75f'
\https://api.instagram.com/oauth/access_token/
Output:
{"access_token": "5351945621.cf07d1a.1d35647e22f24ed0885f65545f3f1b0b", "user": {"id": "5351945621", "username": "abhaykumar", "profile_picture": "https://scontent-amt2-1.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "full_name": "Quantum Four", "bio"}
Curl Url:
https://api.instagram.com/oauth/access_token?client_id=cf07d1a2c69940e59420b6db4c936f4a&client_secret=fb0a975ca2024a1592459308df5ead47&grant_type=authorization_code&redirect_uri=http://localhost:8080/Insta_SMI_M1/auth&code=2c5d97c6d6454b8592816d7d39efb935
The above url neither giving any error nor showing output(its blank line) while using in postman or browser.
Below is the code for same.
#RequestMapping(value="/auth", method=RequestMethod.GET)
public String getAuthCode(HttpServletRequest request, HttpServletResponse response)
{
String code = request.getParameter("code");
System.out.println("code is: "+ code);
String url = "https://api.instagram.com/oauth/access_token?"
+ "client_id=" + Constants.CLIENT_ID
+ "&client_secret=" + Constants.CLIENT_SECRET
+ "&grant_type=authorization_code"
+ "&redirect_uri=" + Constants.REDIRECT_URI_AUTH
+ "&code="+code;
System.out.println("Access Token URL: "+ url);
StringBuffer result = null;
try {
System.out.println("1");
#SuppressWarnings({ "resource", "deprecation" })
HttpClient client = new DefaultHttpClient();
HttpGet request1 = new HttpGet(url);
System.out.println("2");
HttpResponse response1 = client.execute(request1);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response1.getEntity().getContent()));
System.out.println("3");
result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println("line " + line);
result.append(line);
System.out.println("3");
}
} catch (UnsupportedOperationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(result.toString());
return result.toString();
}
Can any body help me with this?
Thanks
The curl is doing a POST request where you are doing a GET request form java. Follow this example about how to make a POST request using java (with http-client). You can consider the following piece of code to set your parameters:
params.add(new BasicNameValuePair("client_id", "cf07d1a2c69940e59420b6db4c936f4a"));
params.add(new BasicNameValuePair("client_secret", "fb0a975ca2024a1592459308df5ead47"));
Since I din't find a complete code to get access token from instagram api on internet , I will put the code below which worked for me.
public String accessTkn (String code)
{
try {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new
HttpPost("https://api.instagram.com/oauth/access_token");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("client_id", Constants.CLIENT_ID));
params.add(new BasicNameValuePair("client_secret", Constants.CLIENT_SECRET));
params.add(new BasicNameValuePair("grant_type", "authorization_code"));
params.add(new BasicNameValuePair("redirect_uri", Constants.REDIRECT_URI_AUTH));
params.add(new BasicNameValuePair("code", code));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("entity "+ entity.getContent());
if (entity != null) {
InputStream instream = entity.getContent();
try {
return (getStringfromStream(instream));
// do something useful
} finally {
instream.close();
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Abhay";
}
Output:
{"access_token": "5351945621.cf07d1a.1d35647e22f24ed0885f65545f3f1b0b", "user": {"id": "5351945621", "username": "abhaykumar", "profile_picture": "https://instagram.fsgn2-1.fna.fbcdn.net/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "full_name": "Abhay Kumar", "bio": "", "website": ""}}
Related
I save data to mysql db with php and json but my data convert to ? ,I use utf-8 in php and db connect and java code
php
<?php
header("Content-type: application/json; charset=utf-8");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
$hostname='localhost';
$username='ekht3r44_6785h5h';
$password='IFVB!8Nw{#-S';
$response = array();
.
.
.
$dbh=new PDO("mysql:host=$hostname;dbname=db;charset=utf8mb4",$username,$password);
$sql="INSERT INTO contact_form (name,email,subject,message) VALUES (".$_POST['name'].",".$_POST['email'].",".$_POST['subject'].",".$_POST['message'].");";
$statement = $dbh->prepare("INSERT INTO contact_form (name,email,subject,message) VALUES (:name,:email,:subject,:message);");
$statement->execute(array(':name' => $_POST['name'],':email' => $_POST['email'],':subject' => $_POST['subject'],':message' => $_POST['message']));
.
.
.
?>
java
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", et_name.getText().toString()));
params.add(new BasicNameValuePair("email", et_email.getText().toString()));
params.add(new BasicNameValuePair("subject", et_subj.getText().toString()));
params.add(new BasicNameValuePair("message", et_msg.getText().toString()));
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
page_output = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return page_output;
}
Can you please check where has it gone wrong.
Please check the charset of your table in MySQL. That "might" be the cause.
Sorry for my english. I cant send json to server. I have error:
{"message":"Customer data is empty!","status":"error"}
Its my example, hov i must send json:
JSON example:
{
"company_id": "1",
"phones": [
"380000505050"
],
"photo": "/files/clients_photos/tmp/484629825.JPG",
"name": "sdfsdfdsf",
"birthdate": "10.02.2014",
"email": "sdf#sdf.ff",
"cars": {
"1": {
"car_brand_id": "9",
"car_model_id": "856",
"number": "AE5884AH",
"photo": "/files/clients_photos/tmp/484629824.JPG"
}
}
}
This is link, where i send json http://crm.pavlun.info/api/register
This is my code:
protected Void doInBackground(String... params) {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postInform = new ArrayList<NameValuePair>();
postInform.add(new BasicNameValuePair("company_id", "2"));
postInform.add(new BasicNameValuePair("phones", "380950466589"));
postInform.add(new BasicNameValuePair("name", "Alexy"));
postInform.add(new BasicNameValuePair("birthdate", "12.03.2014"));
postInform.add(new BasicNameValuePair("email", "nesalexy#mail.ru"));
postInform.add(new BasicNameValuePair("photo", "/files/clients_photos/tmp/484629825.JPG"));
JSONObject registration = null;
try {
Log.e("perform link", postInform.toString()); //its output [company_id=2, phones=380950466589, name=Alexy, birthdate=12.03.2014, email=nesalexy#mail.ru, photo=/files/clients_photos/tmp/484629825.JPG]
registration = operationLink.makeHttpRequest(registrationURL, "POST", postInform);
Log.e("Link", registration.toString()); //its output {"message":"Customer data is empty!","status":"error"}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
This is JSONparser class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
//return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
}
}
I believe I had the same problem previously, strangely enough, servers differ in the way they accept post data.
here is an example
the following method works for a jetty server but not Play:
public static void sendPost(String data,String url) throws Exception{
org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost(url);
org.apache.http.entity.StringEntity entity = new org.apache.http.entity.StringEntity(data.toString());
post.setEntity(entity);
client.execute(post);
}
the followig method works for Play server but not jetty:
public static void sendPostV2(String data, String url) throws Exception{
org.apache.commons.httpclient.HttpClient client =
new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod method =
new org.apache.commons.httpclient.methods.PostMethod(url);
method.addParameter("data", data);
client.executeMethod(method);
method.releaseConnection();
}
we still haven't figured out why, but oh well whatever works baby.
in your case please feel free to use any of the following method (note download the required apache packages). hopefully one of them works for you.
I am trying to send an http post request to a PHP service. Here is an example of how the input may look with some test data
I know that the Java alternative to the PHP associative arrays are HashMaps, but I wonder can this be done with NameValuePairs? What is the best way to format this input and call the PHP service via post request?
Extending #Sash_KP's answer, you can post the nameValuePairs like this too:
params.add(new BasicNameValuePair("Company[name]", "My company"));
params.add(new BasicNameValuePair("User[name]", "My Name"));
Yes this can be done with NameValuePair.You can have something like
List<NameValuePair> params;
//and when making `HttpPost` you can do
HttpPost httpPost = new HttpPost("Yoururl");
httpPost.setEntity(new UrlEncodedFormEntity(params));
//and while building parameters you can do somethin like this
params.add(new BasicNameValuePair("name", "firemanavan"));
params.add(new BasicNameValuePair("cvr", "1245678"));
....
Here's a neat and nice parsing method which you can use.
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
JSONObject jObj = null;
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
And you can simply use it something like
getJSONFromUrl("YourUrl", params);
Now this is just a basic idea of how you can achieve this using NameValuePair.You will have to need some more workaround to implement exactly as you want, but this should provide you the basic idea.Hope this helps.
I'm trying to get a cURL request work in android using the httpclient.
curl -k -X POST \
-F 'image=#00001_1.png;type=image/png' \
-F 'svgz=#00001_1.png;type=image/svg+xml' \
-F 'json={
"text" : "Hello world!",
"tid" : "0010",
"timestamp" : "1342683312",
"location" : [ 22793, -553.3344],
"facebook" :
{
"id": "4444444",
"access_token": "7FUinHfxsCTrx",
"expiration_date": "1358204400"
}
};type=application/json' \
https://example.com/api/posts
This is the code that's giving me a BAD REQUEST ERROR (400) from SERVER.
public static void example() {
HttpClient client = getNewHttpClient();
HttpPost httpost = new HttpPost("https://example.com/api/posts");
httpost.addHeader("image", "#00001_1.png; type=image/png");
httpost.addHeader("svgz", "#00001_1.png; type=image/svg+xml");
httpost.addHeader("type", "multipart/form-data");
// httpost.setHeader("Content-type", "multipart/form-data");
JSONObject data = new JSONObject();
JSONObject facebook = new JSONObject();
JSONArray location = new JSONArray();
HttpResponse response = null;
try {
data.put("text","Hello world!");
data.put("templateid","0010");
data.put("timestamp","2012-07-08 09:00:45.312195368+00:00");
location.put(37.7793);
location.put(-122.4192);
data.put("location", location);
facebook.put("id", "4444444");
facebook.put("access_token", "7FUinHfxsCTrx");
facebook.put("expiration_date", "1358204400");
data.put("facebook", facebook);
System.out.println(" ---- data ----- "+data);
StringEntity stringEntity = new StringEntity(data.toString(), "utf-8");
httpost.setEntity(stringEntity);
try {
response = client.execute(httpost);
System.out.println(" --- response --- "+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if(entity != null) {
// A Simple Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
System.out.println(" ---- result ---- "+result);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
It works perfect from the command line, don't where I'm going wrong. Any help highly appreciated.
Also let me know if I can do it without using any library written in C (Libcurl, etc).
Thanks.
You have used stringEntity to post data. Try using UrlEncodedFormEntity to send data. Here one example how to do:
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("loginId", username.toString()));
nvps.add(new BasicNameValuePair("password", password.toString()));
nvps.add(new BasicNameValuePair("_eventId_submit", "Submit"));
HttpPost httppost = new HttpPost("url2");
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpParams params = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(params, 45000);
HttpConnectionParams.setSoTimeout(params, 45000);
// Perform the HTTP POST request
HttpResponse response = client.execute(httppost);
status = response.getStatusLine().toString();
if (!status.contains("OK")) {
throw new HttpException(status);
}
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie = cookies.get(i);
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm new to http file transfer. I want to send a file from android sdcard to server. For that i tried the below code. I converted the bytes to json string and sent it to the server. But I'm unable to receive it on the server side. I'm using jsp on server side. But there should be some efficient way to do this. Please provide me some ideas.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8084/httptest");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String encodedString = convertURL(jsonString);
nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
tv.setText(responseString);
Log.d("HTTP LOG", responseString);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
jsp
<%
String value = request.getParameter("wavfil");
byte[] wavByte = value.getBytes();
FileOutputStream fos = new FileOutputStream("/TESTFILE.wav");
fos.write(wavByte, 0, wavByte.length);
if (wavByte != null) {
out.println("Success");
} else {
out.println("Failed");
}
%>
Add below lines
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.x.x.x:8084/httptest");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String encodedString = convertURL(jsonString);
nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Create and attach file to the Post
File file = new File("pathto your file"); //replace with actual path
MultipartEntity entity = new MultipartEntity();
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
entity.addPart("file", new FileBody(file));
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
tv.setText(responseString);
Log.d("HTTP LOG", responseString);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}