Android Series: GET, POST and Multipart POST requests
Today I will describe shortly how to execute http GET and POST request on Android platform.
The code is very simple and straightforward, for post request with attachement, you would have to add apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your build path.
HTTP GET
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
HTTP POST
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://somepostaddress.com";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "kris"));
params.add(new BasicNameValuePair("pass", "xyz"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
HttpClient client = new DefaultHttpClient();
String postURL = "http://somepostaddress.com";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "kris"));
params.add(new BasicNameValuePair("pass", "xyz"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
HTTP POST with File attachment
File file = new File("path/to/your/file.txt");
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://someposturl.com";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("myFile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://someposturl.com";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("myFile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps!
Hello,
Thanks for the code, nice work!
My environment doesn’t recognize the classes FileBody and MultipartEntity. Are they available in Android?
Thanks again. Cheers
Yes Jalal, you would have to add apache http libraries to make it work: apache-mime4j-0.6.jar and httpmime-4.0.1.jar on your build path.
Thanks for pointing this out.
Hi Krzysztof,
The code works just fine!!! I still need to authenticate the http client but the multipart post is perfect. Thanks.
Cheers,
Jalal
Hello!
I tried to make http post with file attachment and it compiles, but i get java.lang.illegalstateexception. The code executes but doesn’t post anything. I get status 200 back(OK) and the whole website at EntityUtils.toString(resEntity).
Any comments?
Difficult to tell, is it your website? Do you use same file input field on the web form as in the android code? There can be loads of reasons.
Yes it’s my friend’s website. I used firebug(firefox addon) to get the names of the fields.
Here is the html code,could you please take a look.
public void executeMultipartPost() throws Exception {
try {
//InputStream is = this.getAssets().open(“main.xml”); //c:/reno.jpg taka prava pot za winse
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
“http://dev.jurancic.com/krpovej/kranj.php”);
//postRequest.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
//Log.d(“PARAMETRI PRED ŠTELANJEM”,httpClient.getParams()());
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //tud nc boljs
//httpClient.getParams().setParameter(“http.socket.timeout”, new Integer(115));
httpClient.getParams().setParameter(“http.useragent”, “Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3”);//
httpClient.getParams().setParameter(“http.protocol.content-charset”, “UTF-8”); //veze
httpClient.getParams().setParameter(“http.protocol.reject-relative-redirect”, false);
//httpClient.getParams().setParameter(“http.protocol.max-redirects”, 2);//http.protocol.max-redirects
httpClient.getParams().setParameter(“http.protocol.expect-continue”, false);//dela
//httpClient.getParams().setParameter(“http.protocol.allow-circular-redirects”, true); //dovolimo redirekte na isto lokacijo
//httpClient.getParams().setParameter(“http.connection.stalecheck”, true); veze
//http.connection.stalecheck
//httpClient.getParams().setBooleanParameter(
// “http.protocol.expect-continue”, false); //tole tud ne pomaga
//Log.i(“parametri”,httpClient.getClass().toString());
//byte[] data = IOUtils.toByteArray(is);
//InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), “uploadedFile”);
StringBody zadeva = new StringBody(“Mobi”);
StringBody vsebina = new StringBody(“Test”);
StringBody podrocje = new StringBody(“23”);
StringBody skupina = new StringBody(“6”);
//StringBody mail= new StringBody(“luka@car.com”);
//StringBody telefon = new StringBody(“123456789”);
StringBody poslji=new StringBody(“Pošlji”);
MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //”—————————293582696224464″ ,Charset.forName(“UTF-8”)
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:ddlSkupine”, skupina);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:ddlPodrocja”, podrocje);
//multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtEPosta”, mail);
//multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtTelefon”, telefon);
//multipartContent.addPart(“_ctl8:_ctl1:_ctl0:MultiUpload:File1”, isb);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtZadeva”, zadeva);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtVsebina”, vsebina);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:cmdPoslji”,poslji); //komanda??
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
Log.d(“HTTPKODA”,res.getStatusLine().toString() );
HttpEntity resEntity = res.getEntity();
if (resEntity != null) {
Log.d(“ODGOVOR”,EntityUtils.toString(resEntity));//tole je odgovor
}
httpClient.getConnectionManager().shutdown(); //sprostimo resurse
//res.getEntity().getContent().close(); //ce tole zivo javi napako
} catch (IOException e) {
throw e;
}
}
I also used wireshark to compare http post header that was succesful(via website) and mine from the phone.
There are fewer data in the header in my phone app (accept charset,accept encoding… are missing), so i checked http://hc.apache.org/httpclient-3.x/preference-api.html but couldn’t get the right parameters- maybe the missing parameters are not the cause of the problem.
hope you didn’t get bored by this long post 🙂
Wow!, please do it one step at a time, your code is too messy to work with, but try to send one parameter at a time to see if it gets through, if you need, build simple php/jsp/whatever website to accept those parameters and see if its working, once you got that, you will shift to your friends website.
It’s workig now, my code was working, the bug was on the server. Your snippets are great, tnx!
Thank’s a lot for this code. Works great for me! I was searching for days for a simple way to send multipart post data. Now found it!
Hello!
Does anyone here know how to set encoding in http get request as described above right to display characters (č,š,ž) in response correctly?
I tried with:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
“UTF-8”);
but it’s not working.
Thank you
After getting the response in XML format you can set the Encoding for XML before displaying the data.
Clear simple tutorial . thank you so much
Using your file posting snippet
One Question I am also looking to post data along with with the file..
say i want to add
List nameValuePairs = new ArrayList(7);
…
…
..
when i try to add both list and file only one passes not both.
normally it is only the last to post so in this example only List posts not the file..
Any thoughts
reqEntity.addPart(“ink”, bin);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i(“RESPONSE”,EntityUtils.toString(resEntity));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse responsedata = httpclient.execute(httppost);
HttpEntity resEntitydata = responsedata.getEntity();
if (resEntitydata != null) {
Log.i(“RESPONSE”,EntityUtils.toString(resEntity));
}
Having a problem with multi-part version.
It all runs but the server reports that no file has been uploaded.
$_FILES[‘uploadedfile’][‘name’] =
Any ideas?
Update – FIXED
I had to change “myFile” to “uploadedfile’ in the code to make this work. Duh!
Some people may want to add some other fields, this is how I found to do it:
reqEntity.addPart(“user_name”, new StringBody(uname, “text/plain”, Charset.forName( “UTF-8” )));
BTW – Thanks for the post, it was very helpful.
what will be server code to accept file ?
Hello,
can you post me, server side PHP script, to _POST?
In my access_log :”POST /pp.php HTTP/1.1″ 200 274 “-” “Apache-HttpClient/UNAVAILABLE (java 1.4)”
tnx,
Valentin
hi, thanks for your tutorial..
i tried to executed your sample code in HTTP POST, its successed there are no error line. but in the android emulator, that application did not appear anything, just blank..
any comment?
thanks
Hello Kasper, you would have to specify exactly what do you mean by ‘did not appear anything’, where smth should appear or not? Do you mean LogCat?
So I impletemented this and it works great most of the file, but I’ve found that sometimes when I’m on 3g it will corrupt the upload.
Any Ideas ?
Thanks for nice codes. Cheers!
Thanks for this great code!! However when i run it in the android emulator it takes forever to execute.
I’m I doing anything wrong? What is the server side code that processes the posted file.
I’ll appreciate any help in this regard.
Thanks
Can someone please post the server script also for this code?
you must add permission for internet connection in manifest.xml
Hi,
HTTP POST with File attachment and HTTP POST . both worked for me perfectly. Thanks a lot for this tutorial.
@ Prateek Jain
here is a script that worked for me perfectly.
modify ‘myFile’ to your file name.
PHP SCRIPT:
$target_path = “./”;
$target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]);
if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {
echo “The file “. basename( $_FILES[‘uploadedfile’][‘name’]).
” has been uploaded”;
} else{
echo “There was an error uploading the file, please try again!”;
}
For the http POST example, i will only catch those value by simple $_POST method like:
$user=$_POST[‘user’];
$pass=$_POST[‘pass’];
?
Because right now my php file is only shown a 0 in the page
Hi,
I am stuck somewhr with aproblem.
I need to send a string of data to my server.
the string looks somewhat like :
uniqueIdentifier ~ uniqueIdentifier ~ Question_ID ~ Answered_option ~ Category_ID | uniqueIdentifier ~ uniqueIdentifier ~ Question_ID ~ Answered_option ~ Category_ID |
now how to send this string using HTTPPost ??
Great work!! Thanks!
Great work … Thanks!!!
Nice Article, I have one problem, My response could not retrieve all data at once. Most of return data content Line break with empty string. How do i solve this problem.
Thank you
Thanks Admin. You don’t realize how much you helped me.
Thank you very much.
Hi!
I am getting a runtime error on MultiPartEntity. Looking at logs It says
Could not find class ‘org.apache.http.entity.mime.MultipartEntity’
I have both jars in the lib folder and the code compiles without any errors or warnings but throws runtime exception.
What could be wrong ?
If you run your app from Eclipse, make sure the jar in on the ‘java build path’. Right click on the project, select ‘Build Path’ -> ‘Configure Build Path’ and on the ‘Libraries’ tab look for your dependencies.
I am not using eclipse but building from command line using ant debug command. The jar is in the build path because when I remove file from the libs folder I get compile time error.
my application can not even load into the main page after I using this code…
try {
HttpClient client = new DefaultHttpClient();
String postURL = “http://www.myaddress.com/index.php?action=c.activate&opt=32”;
HttpPost post = new HttpPost(postURL);
List params = new ArrayList();
params.add(new BasicNameValuePair(“id”, “26”));
params.add(new BasicNameValuePair(“status”, “1”));
params.add(new BasicNameValuePair(“time”, “2011-04-06 10:56:00”));
params.add(new BasicNameValuePair(“by”, “Agin Thea”));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
//Log.i(“RESPONSE”,EntityUtils.toString(resEntity));
appML.appManagerShowDialog({message:”Response: “+EntityUtils.toString(resEntityGet)+””,title:”Alert”});
}
} catch (Exception e) {
e.printStackTrace();
}
I have added the two library (apache-mime and httpmime) to the folder libs…
eclipse recognize the code, but when I compile and run in with the Android 2.2 Emulator (API 8), it only showing the loading page it self… (I use appML phoneGap tool for building the application)
Can anyone tell me why the application can not display the main page it self…
These are my codes…
appML demo
@import “themes/jqt/theme.css”;
function appMLReady(){
$(‘#signup_button’).bind(‘click’, function(e, data){
// POST
try {
HttpClient client = new DefaultHttpClient();
“http://www.myaddress.com/index.php?action=c.activate&opt=32”;
HttpPost post = new HttpPost(postURL);
List params = new ArrayList();
params.add(new BasicNameValuePair(“id”, “26”));
params.add(new BasicNameValuePair(“status”, “1”));
params.add(new BasicNameValuePair(“time”, “2011-04-06 10:56:00”));
params.add(new BasicNameValuePair(“by”, “Agin Thea”));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
//Log.i(“RESPONSE”,EntityUtils.toString(resEntity));
appML.appManagerShowDialog({message:”Response: “+EntityUtils.toString(resEntityGet)+””,title:”Alert”});
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
Join us now…
Login
Register
Email:
Password:
Login
Fullname:
Email:
Password:
Register as:
Student
Teacher
Parent
Corporate
Signup
Hello, nice example,
could you how do i send multipart and post params ?
sir , i want an example on android for send request/ get response from . please send me full code .
Hi thanks for nice article.
how can i send japanese character to my script(php).
i am sending some jp chars and it is inserted in mysql db succesfully but the chars are garbaged.
nameValuePairs.add(new BasicNameValuePair(“name”, “aaaあいうえお亜”));
form = new UrlEncodedFormEntity(nameValuePairs);
form.setContentEncoding(HTTP.UTF_8);
//form.
httppost.setEntity(form);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
how to solve it?
I need to post data along with file but i cannot add authorization data and file to one request. Could you please explain how to act in this situation?
Thanks in advance,
NewCommer
Hi,
This one is Good code but error arriving that file posted is empty.
i am giving the path like sdcard\filename.pcm…
what is the solution for this problem.
Where do you get those two libraries?
How do i add a file to the http post if i dont want to use MutlipartEntity. For example if I have an array like below how will i call the video?
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(“url”);
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair(“user_email”, useremail));
nvps.add(new BasicNameValuePair(“friend_email”, friendemail));
nvps.add(new BasicNameValuePair(“Application Key”, app_key));
nvps.add(new BasicNameValuePair(“Client Code”, client_code));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,
HTTP.UTF_8);
httppost.setEntity(p_entity);
HttpResponse responsePOST = client.execute(httppost);
Could it b as simple as adding:
//httppost.setEntity(new FileEntity(file,”Video”));
I want to send like:
(server side code)
$params = array(‘user’ => array(
‘firstname’ => ‘Bob Smith’,
‘lastname’ => ‘Johnson’
));
But unable to do so in java/android.
it is getting force closed.Do I need to give any additional permission apart from internet
Hi , I wanted to know that if I am sending data in some entity in the httpPost, then how do I get the data in the servlet at my server.
regards
Shankar
Hi,
I an trying to get some list of values from the server( where it is stored) how can I get that, and also the I have to Post some data to server.
This is a great article.Congratulations.
I hava a curious problem posting a file onto my server (I have a PHP script running).The problem is:
$_SERVER[‘REQUEST_METHOD’] returns GET, but it is a POST request right?
Any suggestions?
Thanks for your support
I don’t knwo how many tutorials I’ve done and I thought your example would work, but still the same error happened. It always stops on
HttpResponse response = client.execute(get);
Permissions to the internet I have in the manifest. Please help.
Sir,,
I have a problem in using MultipartEntity. my data is not getting saved in database , ,,,
But if i directly passing my variables in Url its get saved ,, tell me where is the Problem?????
http://xxxxxxxxx/api/index.php?method=postClassified&location=1
If you are passing params with the url it means you are using GET request, you would have to use POST for multipart requests.
try {
HttpClient client = new DefaultHttpClient();
String getURL = “http:192.168.1.5:8080/one/try.jsp”;
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i(“GET RESPONSE”,EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
TextView tv=new TextView(this);
tv.setText(e.getMessage());
setContentView(tv);
}
it displays host name may not be null
dun know wats wrong its been 3 days i am not able access jsp file on local host
client.execute() is generating exception
thanks you advanced! by your guide, I more understand about http get and http post and use it on Android :)! Thanks again
Hi Sir
I run the get method by Button.Click.My code is as below.
I can not see reponse from Yahoo page.
Could you give me some suggestion?
Thansk a lot
private Button.OnClickListener test=new OnClickListener(){
public void onClick(View v) {
try {
HttpClient client = new DefaultHttpClient();
String getURL = “http://www.google.com”;
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
textView1.setText(responseGet.getStatusLine().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
};
Hi sir
I use post with file code to test. It had information as below.
Could you give me some suggestion?
Thanks
———————-
07-25 15:11:55.502: E/dalvikvm(11952): Could not find class ‘org.apache.http.entity.mime.content.FileBody’, referenced from method tw.tcc.tsvs.www.FileUploadPost.FileUploadPostActivity$1.onClick
07-25 15:11:55.502: W/dalvikvm(11952): VFY: unable to resolve new-instance 38 (Lorg/apache/http/entity/mime/content/FileBody;) in Ltw/tcc/tsvs/www/FileUploadPost/FileUploadPostActivity$1;
07-25 15:11:55.502: D/dalvikvm(11952): VFY: replacing opcode 0x22 at 0x0013
07-25 15:11:55.502: D/dalvikvm(11952): DexOpt: unable to opt direct call 0x001f at 0x15 in Ltw/tcc/tsvs/www/FileUploadPost/FileUploadPostActivity$1;.onClick
07-25 15:11:55.512: D/dalvikvm(11952): DexOpt: unable to opt direct call 0x001d at 0x1c in Ltw/tcc/tsvs/www/FileUploadPost/FileUploadPostActivity$1;.onClick
07-25 15:12:02.709: D/AndroidRuntime(11952): Shutting down VM
07-25 15:12:02.709: W/dalvikvm(11952): threadid=1: thread exiting with uncaught exception (group=0x40abf228)
07-25 15:12:02.729: E/AndroidRuntime(11952): FATAL EXCEPTION: main
07-25 15:12:02.729: E/AndroidRuntime(11952): java.lang.NoClassDefFoundError: org.apache.http.entity.mime.content.FileBody
07-25 15:12:02.729: E/AndroidRuntime(11952): at tw.tcc.tsvs.www.FileUploadPost.FileUploadPostActivity$1.onClick(FileUploadPostActivity.java:76)
07-25 15:12:02.729: E/AndroidRuntime(11952): at android.view.View.performClick(View.java:3538)
07-25 15:12:02.729: E/AndroidRuntime(11952): at android.view.View$PerformClick.run(View.java:14330)
07-25 15:12:02.729: E/AndroidRuntime(11952): at android.os.Handler.handleCallback(Handler.java:607)
07-25 15:12:02.729: E/AndroidRuntime(11952): at android.os.Handler.dispatchMessage(Handler.java:92)
07-25 15:12:02.729: E/AndroidRuntime(11952): at android.os.Looper.loop(Looper.java:154)
07-25 15:12:02.729: E/AndroidRuntime(11952): at android.app.ActivityThread.main(ActivityThread.java:4974)
07-25 15:12:02.729: E/AndroidRuntime(11952): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 15:12:02.729: E/AndroidRuntime(11952): at java.lang.reflect.Method.invoke(Method.java:511)
07-25 15:12:02.729: E/AndroidRuntime(11952): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-25 15:12:02.729: E/AndroidRuntime(11952): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-25 15:12:02.729: E/AndroidRuntime(11952): at dalvik.system.NativeStart.main(Native Method)
Hey Thanx…
Your post really helped me a lot
How can i prepare a simple PHP file to use it for HttpPOST request…? I’m new to android as well as PHP…can someone please help me…I gotta complete my project within 10 days…please…please…
Thanks in advance,and I’ll be eagerly waiting for your replay…
How can i prepare a simple PHP file to use it for HttpPOST request…? I’m new to android as well as PHP…can someone please help me…I gotta complete my project within 10 days…please…please…
Thanks in advance,and I’ll be eagerly waiting for your replay…
HttpClient client = new DefaultHttpClient();
String postURL = “http://222.252.96.173/emsportal/DesktopDefault.aspx?tabindex=5&tabid=136&lanid=VN”;
HttpPost post = new HttpPost(postURL);
List params = new ArrayList();
params.add(new BasicNameValuePair(“ctl03$Mae1_txt”,”EI460165665VN”));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
System.out.println(EntityUtils.toString(resEntity));
no result traced.
Please help me fix
Good info. THanks for the HTTPGET 🙂
Hey! Would you mind if I share your blog with my myspace group?
There’s a lot of folks that I think would really enjoy
your content. Please let me know. Thanks
no problem
i done it login api is working
i use volly library
add volly library in gradle file (compile ‘com.mcxiaoke.volley:library:1.0.19’)
then write this code by hand not copy past 😛
i hope it is working inshALLAH
package com.example.akdawran.login;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
private EditText user,pass;
private Button loginme;
private RequestQueue requestQueue;
private static final String URL = “Enter your API”;
private StringRequest request;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue = Volley.newRequestQueue(this);
loginme = (Button) findViewById(R.id.btn_login);
user = (EditText) findViewById(R.id.UserNameEditText);
pass = (EditText) findViewById(R.id.PasswordEditText);
loginme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener(){
public void onResponse (String response){
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals(“status”)){
Toast.makeText(getApplicationContext(),” ! “+jsonObject.getString(“message”),Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MaterialTabs.class));
}else {
Toast.makeText(getApplicationContext(), “Error” +jsonObject.getString(“error”), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map getParams() throws AuthFailureError {
HashMap hashMap = new HashMap();
hashMap.put(“Email”,user.getText().toString());
hashMap.put(“password”,pass.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});
}
}
best of luck.
My write-up about pdf book has several opposite factors to
Android Series: GET, POST and Multipart POST requests