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();
}
Related
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": ""}}
I am working on an application in that i have developed ios code for making a webservice call and it is giving me response successfully,The same webservice call when i am trying to call in android it is not working it is not giving me response,I am posting my both code,Can anybody help me to figure it?
ios code
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#",k_SERVER_BASE_ADDRESS,service_name]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
[request setValue:[NSString stringWithFormat:#"%#",k_CONTENT_TYPE] forHTTPHeaderField:#"Content-Type"];
// 3
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_USER_NAME] forKey:#"APIUserName"];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_PASSWORD] forKey:#"Password"];
NSLog(#"%#",dictionary);
NSError *error = nil;
NSData *data_prm = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
NSLog(#"%#",[[NSString alloc] initWithData:data_prm encoding:NSUTF8StringEncoding]);
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data_prm completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here..
NSLog(#"this is data : %#",data);
Android Code
public class GETCONTESTANTS extends AsyncTask<Void, Void, Void> {
StringEntity se;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
// stateList.clear();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants");
String json = "";
try {
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jsonObject.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
se = new StringEntity(json);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
In above codes "iOS code" is working fine and "android code" is not working. Can anyone please help me?
try this snippet of code may be helpful
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
String url="http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
JSONObject jo = null;
jo = new JSONObject();
try {
jo.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jo.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject job=new JSONObject();
try {
job.accumulate("aloha", jo);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.e("url", job.toString());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
try {
httppost.setEntity(new StringEntity(job.toString(), "UTF- 8"));
// httppost.toString();
// Log.e("url", httppost.toString());
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
Log.e("url", json);
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}
I am using Commons HttpClient to send a post request along with some string content as parameter. Following is my code:
// obtain the default httpclient
client = new DefaultHttpClient();
// obtain a http post request object
postRequest = new HttpPost(stanbolInstance);
postRequest.setHeader("Accept", "application/json");
// create an http param containing summary of article
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", content));
try {
// add the param to postRequest
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// obtain the response
response = client.execute(postRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here, stanbolInstance is: http://dev.iks-project.eu:8081/enhancer
It does not work. Following is the exception:
Problem accessing /enhancer. Reason:
<pre> The parsed byte array MUST NOT be NULL!</pre></p><h3>Caused by:</h3><pre>java.lang.IllegalArgumentException: The parsed byte array MUST NOT be NULL!
Following is the cURL equivalent which works:
curl -X POST -H "Accept: text/turtle" -H "Content-type: text/plain" --data "The Stanbol enhancer can detect famous cities such as Paris and people such as Bob Marley." http://dev.iks-project.eu:8081/enhancer
Help!
I think you're putting the content in the wrong way.
Replace:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", content));
try {
// add the param to postRequest
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
with
postRequest.setEntity(new StringEntity(content));
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
}
I am trying to post xml on android. Same xml and server works on iphone perfectly, but on android i am getting invalid xml error message.
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://stage.isadiasjd.com.tr/asdasdad-web/getProductDeviceService.do");
try {
StringEntity se = new StringEntity("<customer><districtId>2541</districtId><barcode>45464654654917</barcode><udid>dade51ce2c127310d1df5ee25e876e46feae470b</udid><email>Xzcxzcxzczxc#zxczxcxczxc.com</email><hashCode>2500a7005c01903093fa268984zczczczaeawdwa2w1d3w6dec9b61afbe28f37baad819ba3e0d</hashCode></customer>", "UTF-8");
// se.setContentType("text/xml");
se.setContentType("application/atom+xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String ss = EntityUtils.toString(resEntity);
Log.v("http req", ss);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.v("ex","1");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("ex","2");
e.printStackTrace();
}
}
Try application/json. On Android 2 something wrong with xml responses on some models