Https post request using curl : Android - java

I am trying to execute a https post request using curl. When I execute this request, I am neither getting any response nor any error or exception. Help or any clue about what's going wrong here is appreciated. Thanks.
curl command line format :
curl -X POST \
-F 'image=#filename.png;type=image/png' \
-F 'svgz=#filename.svgz;type=image/svg+xml' \
-F 'json={
"text" : "Hello world!",
"templateid" : "0010",
"timestamp" : "1342683312",
"location" : [ 37.7793, -122.4192 ],
"facebook" :
{
"id": "738124695",
"access_token": "<VALID_USER_FACEBOOK_TOKEN_WITH_PUBLISH_ACTIONS_PERMISSIONS",
"expiration_date": "1342683312"
}
};type=application/json' \
https://sample.com/api/posts
Facebook posting code :
public static void uploadToFB() {
HttpClient client = getNewHttpClient();
HttpPost httpost = new HttpPost("https://sample.com/api/posts");
httpost.addHeader("image", "filename.png");
httpost.addHeader("svgz", "filename.svgz");
httpost.addHeader("type", "application/json");
httpost.setHeader("Content-type", "application/json");
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", "738124695");
facebook.put("access_token", "AAADdF92joPABAKmRojBuXZAZAP"+
"qF8ZAxM2bM"+
"UnIErUSYZB85y5vIHAZDZD");
facebook.put("expiration_date", "2013-07-07T 22:00:00Z");
data.put("facebook", facebook);
System.out.println(" ---- data ----- "+data);
StringEntity stringEntity = new StringEntity(data.toString());
httpost.setEntity(stringEntity);
try {
response = client.execute(httpost);
System.out.println(" --- response --- "+response);
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 was an untrusted network, so, for that I did something like below as in this link.
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}

BufferedReader in = null;
StringBuffer sb = new StringBuffer();
BufferedReader inPost = null;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(mURL);
httpost.setHeader("Accept","*/*");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List <NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("testkey1", "myvalue1"));
nvps.add(new BasicNameValuePair("testkey2", "myvalue2"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
inPost = new BufferedReader(new InputStreamReader(entity.getContent()));
String linePost = "";
String NLPOST = System.getProperty("line.separator");
while ((linePost = inPost.readLine()) != null) {
sb.append(linePost + NLPOST);
}
inPost.close();
if (entity != null) {
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
also more on this link..
http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/

After some hard time I got solution for my problem. Now, using MultipartEntity, I am able to send data to server like below.
HttpClient httpClient = getHttpClient();
HttpPost httpost = new HttpPost("https://sample.com/api/posts");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile1 = new FileBody(new File("file.png"), "image/png");
mpEntity.addPart("image", cbFile1);
ContentBody cbFile2 = new FileBody(new File("file.svg"), "image/svg+xml");
mpEntity.addPart("svgz", cbFile2);
ContentBody cbFile3 = new StringBody(getJsonData().toString(), "application/json", Charset.forName("UTF-8"));
mpEntity.addPart("json", cbFile3);
httpost.setEntity(mpEntity);

Related

how to post (parameters) and get the response from Httpclient and Httppost in android

I want correct response from web server. The structure of my json response is like this.
{
"message": "Successfully",
"profile": {
"name": "myname",
"mail": "mymail",
"sex" : sex
}
}
But I always get the response as below.
{
"message": "failed"
}
Below is my code.
String url ="myurlXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
JSONObject json1 = new JSONObject();
json1.put("name", myname);
json1.put("mail", mymail);
json1.put("sex", sex);
HttpClient client = new DefaultHttpClient();
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-type", "application/json");
post1.setHeader("Accept", "application/json");
post1.setEntity(new StringEntity(json1.toString(), "UTF-8"));
HttpResponse httpresponse = client.execute(post1);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Is there anything wrong? Anyone please help me. Thanks in advance
Try replace the code for this:
JSONObject json2 = new JSONObject();
JSONObject json1 = new JSONObject();
json1.put("name", myname);
json1.put("mail", mymail);
json1.put("sex", sex);
json2.put("message", "Successfully");
json2.put("profile", json1);
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-type", "application/json");
post1.setHeader("Accept", "application/json");
post1.setEntity(new StringEntity(json2.toString(), "UTF-8"));
HttpResponse httpresponse = client.execute(post1);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
hope it helps

Android - How to upload video/image to PHP Server

I am able to post string values to PHP server by using the following code:
public void callWebService(String strEmailList){
HttpResponse response = null;
String responseBody="";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("stringkey1",
String_Value1));
nameValuePairs.add(new BasicNameValuePair("stringkey2", String_Value2));
nameValuePairs.add(new BasicNameValuePair("stringkey3", String_Value3));
nameValuePairs.add(new BasicNameValuePair("stringkey4", String_Value4));
nameValuePairs.add(new BasicNameValuePair("stringkey5", String_Value5));
nameValuePairs.add(new BasicNameValuePair("stringkey6", Here i need to post Image));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY URL");
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handleResponse(responseBody);
}
I am getting responseBody perfectly if i post only string values. In the nameValuePair, I need to post Image to Server. Can anyone help me how to post image using following code.
You can send image to the server as a Multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
For uploading image and Video,,, you need to use MultiPart.First you need to Attach your file in fileBody which later attach in Multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, String taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception 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");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++)
{
if (index == nameValuePairs.size()-1)
{
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
entity.addPart(nameValuePairs.get(index).getName() , new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String resdata = EntityUtils.toString(resEntity);
System.out.println("DATA :" + resdata);
}
} catch (IOException e) {
e.printStackTrace();
}

App crashes on httGet when attempting to send to Json?

My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;

Android 4.0.3 https post returns empty, http works, both works on 2.0.3

I'm connecting my Application to a REST type webservice. I'm using the apache http library, the request is a standard post request, ran in a background thread.
Now my problem is that if I'm using
http://myserver.com/api/command
it works and I get the proper response, but the same url with https:
https://myserver.com/api/command
I get an empty response. The http header is even 200 OK.
BOTH of these work on 2.0.3 but not on 4.0.3. On 4.0.3 the API seems to work only if I use plain http, with https I get empty responses.
This is the code:
#Override
protected HttpResponse doInBackground(String... params) {
String link = params[0];
HttpClient client = createHttpClient();
try {
HashMap<String, ContentBody> files = ApiManager.getFiles();
MultipartEntity mpEntity = new MultipartEntity();
if(files != null) {
for(String i : files.keySet()) {
ContentBody k = files.get(i);
mpEntity.addPart(i, k);
}
}
if(this.callParameters != null) {
for(NameValuePair i : this.callParameters) {
StringBody sb = new StringBody((String)i.getValue(),"text/plain",Charset.forName("UTF-8"));
mpEntity.addPart(i.getName(), sb);
}
}
httppost.setEntity(mpEntity);
// Execute HTTP Post Request
Log.d("ApiTask","Executing request: "+httppost.getRequestLine());
HttpResponse response = null;
response = client.execute(httppost);
client.getConnectionManager().shutdown();
return response;
}
catch(UnknownHostException e) {
exception = e;
return null;
}
catch (IOException e) {
exception = e;
return null;
}
catch(Exception e) {
return null;
}
}
#Override
protected void onPostExecute(HttpResponse result) {
System.out.println("STATUS:"+result.getStatusLine());
try {
StringBuilder responseText = this.inputStreamToString(result.getEntity().getContent());
System.out.println("RESPONSE:"+responseText);
}
catch(Exception e) {
System.out.println("Error");
}
}
private HttpClient createHttpClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
Thank you in advance

Slow upload speeds using HttpClient, Jame's Mime4j and HttpPost method of posting

I'm uploading a multipart chunk of data using HttpPost and feeding it into an HttpClient objects execute method as follows:
HttpPost loginPost = new HttpPost(LOGIN_URL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("_email", mEmailAddress));
params.add(new BasicNameValuePair("lpassword", mPassword));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
loginPost.setEntity(entity);
HttpResponse resp = mHttpClient.execute(loginPost);
HttpPost post = new HttpPost(UPLOAD_URL);
FileBody bin = new FileBody(file);
MultipartEntity me = new MultipartEntity();
me.addPart("stuff", new StringBody(stuff));
me.addPart("file", bin);
post.setEntity(new RequestEntityEx(me, handler));
mHttpClient.execute(post);
Now, logging in and posting work - fine but uploading is painfully slow. I've tested my internet connection and it's far slower than what it should be (approx. up speed is 1Mb/s, uploading a 3MB file is taking around 5 minutes (rather than 30s).
Anyone have any ideas?
I've found that HttpClient is like 9 times slower than regular way on https. I have no idea why, anybody knows what's wrong.
Here is basically my code
private static HttpClient httpClient = new DefaultHttpClient();
private static HttpPost httpPost = new HttpPost(RRD_URL);
public static String sendData(List<NameValuePair> data) {
StringBuffer buffer = new StringBuffer();
BufferedReader rd = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse httpResponse = httpClient.execute(httpPost);
rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace(System.out);
} finally {
try {
if (rd != null) {
rd.close();
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
return buffer.toString();
}

Categories

Resources